Tuesday, September 21, 2010

I hate hibernate

today's problem
I see it reported by others as well:
http://www.theserverside.com/discussions/thread.tss?thread_id=37010
http://www.coderanch.com/t/422591/ORM/java/Hibernate-one-many-association-foreign


foreign keys when the column name on child side differs from the primary key

in JOB_HRD mapping file, key is JOB_DI, foreign column is SERVICE_ID
<set name="SERVICES" cascade="all" inverse="true" lazy="true" outer-join="auto">
<key column="ID"/>
<one-to-many class="at.oeamtc.oop.hybernate.Services"/>
</set>
the generated join query is JOB_HDR.JOB_ID = SERVICE.ID and not the wanted one : JOB_HDR.SERVICE_ID = SERVICE.ID

second attempt to use many-to-one
<many-to-one name="services" class="at.oeamtc.oop.hybernate.Services" insert="false" update="false">
<column name="SERVICE_ID"></column>
</many-to-one>
when there is property SERVICE_ID in the mapping file

first complained that there is such a property SERVICE_ID and that update and insert into many-to-one should be set to false; after set to false, it complains that it cannot set the corresponding property (in this case services in JobHeader class)...

the only solution found, to remove the other mapping of SERVICE_ID

and all these to be able to write a join subquery with Criteria API...

-------------------
finally solved:
dual mapping on SERVICE_ID is possible but beside update='false' and insert='false' it is needed also cascade='none':
<many-to-one name="service" class="at.oeamtc.oop.hybernate.Services" cascade="none" insert="false" update="false" >
<column name="SERVICE_ID"></column>
</many-to-one>

getter and setter methods to be defined in java bean class, this time no setter is called in the constructor (as I did the previous time)

and the query is:
Criteria criteria = session.createCriteria(Jobs.class);
//add restrictions / expressions

//join with job_header
criteria = criteria .createCriteria("JOB_HDR");
//add further restrictions / expressions

//join with service:
//note that service is the name of many-to-one relationship in the mapping file
//as above JOB_HDR is many-to-one in the mapping file for jobs
crit = crit.createCriteria("service").add(Expression.eq("IS_57", serviceTypeId));

No comments:

Post a Comment