Hibernate一对一XML映射

时间:2013-08-24 00:41:14

标签: 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 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检索的ProfileprofileId的{​​{1}}相同userId,即如果UseruserId 4 Profile检索到的profileIdProfile 4的配置文件,即使它应该检索userId 1}} 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; } } 4。

更新:添加Dao代码

{{1}}

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。最初,我每次需要手动设置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 xml user的{​​{1}}中,然后将Profile添加到property-ref="user" one-to-one中的userProfile。我认为这里的关键是User