我找到了以下链接:
但似乎没有任何效果。
我有 2 个实体:
class User {
Integer userId;
Profile userProfile;
}
class Profile {
Integer profileId;
User user;
}
使用 XML 映射:
<?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 by 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>
这里的问题是,User
必须有一个Profile
,但Profile
不一定有一个User
,所以 aProfile
可能有null
User
。
现在的问题是每次我获取User
与其关联Profile
的 a 时,Profile
检索到的都是Profile
与profileId
相同的userId
,也就是说,如果User
有userId
4,则Profile
检索到的配置文件也是profileId
4,即使它应该Profile
用userId
4 而不是profileId
4 检索。
更新:添加道代码
public User findById( int id ) {
log.debug("getting User instance with 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;
}
}