我找到了以下链接:
- Hibernate one to one mapping problem
- Hibernate one-to-one mapping with a reference column (XML mapping)
- hibernate one-to-one (on foreign key) vs one-to-one (on primary key)
但似乎没有任何效果。
我有 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
因此,Profile
可能具有 null
User
。
现在的问题是,每次我获取 User
及其关联的 Profile
时,检索到的 Profile
就是 Profile
code> 的 profileId
与 userId
相同,也就是说,如果 User
的 userId
4 则 检索到的配置文件
也是profileId
4的配置文件,即使它应该检索userId
4而不是的
4.Profile
profileId
更新:添加 Dao 代码
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;
}
}
最佳答案
终于找到解决办法了。最初我必须设置 userProfile
每次我需要手动获取关联的 userProfile
时的User
只是为了临时解决方法。但我刚刚找到了这个链接:http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html#assoc-bidirectional-121
所以基本上我只需要添加 unique="true" not-null="false"
到many-to-one
user
的在Profile
xml 并添加 property-ref="user"
到one-to-one
userProfile
在User
。我认为这里的关键是 property-ref="user"
关于java - Hibernate 一对一 XML 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413783/