Java Hibernate一对一XML映射
我找到了以下链接:Java Hibernate一对一XML映射,java,spring,hibernate,Java,Spring,Hibernate,我找到了以下链接: 但似乎什么都不管用 我有两个实体: class User { Integer userId; Profile userProfile; } class Profile { Integer profileId; User user; } 使用XML映射: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
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>
最后我找到了解决办法。最初,每次需要获取
用户的相关userProfile
时,我都必须手动设置userProfile
,只是为了临时解决问题。但我刚刚找到了这个链接:
因此,基本上我只需将unique=“true”notnull=“false”
添加到Profile
xml中用户的多对一中,并将属性ref=“user”
添加到用户的一对一用户配置文件中。我认为这里的关键是property ref=“user”
你能分享你的DAO代码吗?我总是倾向于将一对一
属性映射为多对一
,在DB外键中有一个唯一的约束。我不知道这是否能解决您的问题,但您可以尝试在您的用户
中映射用户配置文件
,方法与您的配置文件
实体中的用户
类似。
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;
}
}