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;
    }
}