java - Hibernate one-to-one XML mapping -
i found following links:
- hibernate 1 one mapping problem
- hibernate one-to-one mapping reference column (xml mapping)
- hibernate one-to-one (on foreign key) vs one-to-one (on primary key)
but nothing seems work.
i have 2 entities:
class user { integer userid; profile userprofile; } class profile { integer profileid; user user; } with xml mapping:
<?xml version="1.0"?> <!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="model.user" table="user" catalog="proj1" dynamic-update="true"> <id name="userid" type="java.lang.integer"> <column name="userid" /> <generator class="identity" /> </id> <one-to-one name="userprofile" class="model.profile"> </one-to-one> </class> </hibernate-mapping> <?xml version="1.0"?> <!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- generated jun 12, 2013 7:51:22 pm hibernate tools 3.4.0.cr1 --> <hibernate-mapping> <class name="model.profile" table="profile" catalog="proj1" dynamic-update="true"> <id name="profileid" type="java.lang.integer"> <column name="profileid" /> <generator class="identity" /> </id> <many-to-one name="user" class="model.users" unique="true"> <column name="userid" /> </many-to-one> </class> </hibernate-mapping> the thing here is, user must have 1 profile profile doesn't have 1 user profile may have null user.
now problem every time fetch user associated profile, profile retrieved profile profileid same userid, if user has userid 4 profile retrieved profile profileid 4 though supposed retrieve profile userid 4 not profileid 4.
update: add dao code
public user findbyid( int id ) { log.debug("getting user instance id: " + id); try { criteria usercriteria = this.sessionfactory.getcurrentsession().createcriteria(user.class); usercriteria.add(restrictions.ideq(id)); usercriteria.setfetchmode("userprofile", fetchmode.join); usercriteria.setresulttransformer(criteriaspecification.distinct_root_entity); users instance = (users) usercriteria.uniqueresult(); if(instance == null) log.debug("get successful, no instance found"); else log.debug("get successful, instance found"); return instance; } catch(runtimeexception re) { log.error("get failed", re); throw re; } }
finally found solution. had set userprofile manually every time need fetch associated userprofile of user temporary workaround. found link: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html#assoc-bidirectional-121
so have add unique="true" not-null="false" many-to-one of user in profile xml , add property-ref="user" one-to-one userprofile in user. think key here property-ref="user"
Comments
Post a Comment