1

我找到了以下链接:

但似乎没有任何效果。

我有 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检索到的都是ProfileprofileId相同的userId,也就是说,如果UseruserId4,则Profile检索到的配置文件也是profileId4,即使它应该ProfileuserId4 而不是profileId4 检索。

更新:添加道代码

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

1 回答 1

0

最后我找到了解决方案。最初,userProfile每次我需要获取关联userProfile的 a时,我都必须手动设置,User只是为了临时解决问题。但我刚刚找到了这个链接:http ://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html#assoc-bidirectional-121

所以基本上我只需要添加到unique="true" not-null="false"in xml并添加many-to-one到in . 我认为这里的关键是userProfileproperty-ref="user"one-to-one userProfileUserproperty-ref="user"

于 2013-08-26T07:29:13.720 回答