我有一个User对象,它有一个与之关联的UserProfile对象,每个对象都有自己的数据库表。我已经使用双向映射将hibernate映射设置为级联操作,这样我就可以在User对象上调用Save,它将自动创建用户配置文件对象,在单个操作中插入生成的UserId in key列。这很好用。 Hibernate映射如下
<class name="User" table="[User]">
<id name="UserId" unsaved-value="0">
<generator class="identity" />
</id>
<property name="FirstName" />
<property name="LastName" />
<property name="EmailAddress" />
<property name="DateOfBirth" />
<property name="Gender" />
<property name="PostcodePartOne" />
<property name="PostcodePartTwo" />
<many-to-one name="UserLocation" column="UserLocationId" />
<property name="DateJoined" />
<property name="LastLoggedOn" />
<property name="Status"/>
<property name="StatusNotes" />
<one-to-one name="Profile" class="UserProfile" cascade="all" />
</class>
<class name="UserProfile" table="UserProfile">
<id name="UserProfileId" column="UserId">
<generator class="foreign">
<param name="property">User</param>
</generator>
</id>
<one-to-one name="User" class="User" constrained="true" />
<property name="Height" />
<many-to-one name="BodyType" column="BodyTypeId" />
<many-to-one name="Ethnicity" column="EthnicityId" />
<many-to-one name="MaritalStatus" column="MaritalStatusId"/>
<property name="NumberOfChildren" />
<many-to-one name="WantsChildren" column="WantsChildrenId" />
<many-to-one name="Religion" column="ReligionId" />
<many-to-one name="Drinking" column="DrinkingId" />
<many-to-one name="Smoking" column="SmokingId" />
<many-to-one name="Diet" column="DietId" />
<many-to-one name="Education" column="EducationId" />
<many-to-one name="Socialising" column="SocialisingId" />
<many-to-one name="Travelling" column="TravellingId" />
<many-to-one name="Romance" column="RomanceId" />
<many-to-one name="SexualOpenness" column="SexualOpennessId" />
<many-to-one name="SexualFrequency" column="SexualFrequencyId" />
<many-to-one name="SharedInterests" column="SharedInterestsId" />
<many-to-one name="TimeWithPartner" column="TimeWithPartnerId" />
<many-to-one name="Ambition" column="AmbitionId" />
<many-to-one name="Emigrating" column="EmigratingId" />
<many-to-one name="FamilyInvolvement" column="FamilyInvolvementId" />
<property name="LastUpdated" />
<one-to-one name="ProfileText" class="UserProfileText" cascade="all" />
</class>
当我尝试进行分离更新时,什么不起作用。我创建了一个新的User和UserProfile对象,将它们与我保存时的引用相互链接,然后将User.UserId分配给我想要更新的已保存用户ID。然后我调用session.merge(用户)但得到以下错误
Message "Error updating item of type 'User':a different object with the same identifier value was already associated with the session: 153, of entity: UserProfile" string
这是否告诉我,它很乐意合并User对象但由于某种原因无法合并用户配置文件?
我做错了什么?
答案 0 :(得分:0)
认为我发现了问题。我正在将UserProfiles“User”属性引用设置为父User对象,但是我没有设置它作为PK的“UserId”属性,因此它认为它属于父用户但仍为其UserId为零标识符。在Profile对象上设置UserId以及User对象工作