A
A
Alexiuscrow2016-02-02 14:15:04
Hibernate
Alexiuscrow, 2016-02-02 14:15:04

Hibernate. How to build sql query in xml?

There is a mapping xml file:

<?xml version="1.0" ?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.example.MyObject" table="OWNER"
           where="service = 462">

        <id name="id" column="id" unsaved-value="null"/>

        <property name="name" column="name"  insert="false" update="false"/>
        <property name="description" column="description" insert="false" update="false"/>

    </class>
</hibernate-mapping>

The MyObject class must also contain a set of objects of the HerObject class:
<set name="herObjects" lazy="false">
        <key />
        <one-to-many class="com.example.HerObject"/>
</set>

but you need to get herObjects using a complex sql query. To do this, I specify the construction (in the example, sql is simplified):
<sql-query name="herObjSQLQuery">
        <load-collection alias="ho" role="com.example.MyObject.herObjects"/>
        <![CDATA[
        select {ho.*} from her_obj ho where owner_id = :id
        ]]>
</sql-query>

, where instead of :id, as planned, the id of the current element of MyObject should be substituted. I also added the following line to the set block:
<loader query-ref="com.example.MyObject.herObjSQLQuery" />

The result is the following xml:
<?xml version="1.0" ?>
    <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
        <class name="com.example.MyObject" table="AAA"
               where="service = 462 and status = 1 and conference_number > 0">

            <id name="id" column="id" unsaved-value="null"/>

            <property name="name" column="name"  insert="false" update="false"/>
            <property name="description" column="description" insert="false" update="false"/>

            <set name="herObjects" lazy="false">
                   <key />
                   <one-to-many class="com.example.HerObject"/>
                   <loader query-ref="com.example.MyObject.herObjSQLQuery" />
            </set>

            <sql-query name="herObjSQLQuery">
                   <load-collection alias="ho" role="com.example.MyObject.herObjects"/>
                   <![CDATA[
                   select {ho.*} from her_obj ho where owner_id = :id
                   ]]>
            </sql-query>

        </class>
    </hibernate-mapping>

Where is the mistake? How to substitute the current value of the id of the MyObject object in a sql query?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question