【问题标题】:Hibernate, saving a collection property in a single operation休眠,在单个操作中保存集合属性
【发布时间】:2013-03-19 19:29:09
【问题描述】:

我需要更好地了解休眠的这种行为,并想知道我是否可以对此事有所了解。 有两个对象 ContactAction 具有一对多关系,即一个 Contact 可以有许多 Actions 与之关联。 我想了解的是,当我将Contact 存储到数据库时,如何存储Actions 的集合(这是Contact 的属性)。 目前我正在做的是先存储Contacts,然后存储Actions。 以下是我的代码: 模型对象:

public class Contact  implements Serializable{
    private Integer contactID;
    private String givenName;
    private String familyName;
    private Set<Action> actionSet = new HashSet<Action>();
}
public class Action  implements Serializable{
    private Integer actionID;
    private String actionNote;
    private Contact contact;
}

休眠映射:

<hibernate-mapping package="com.hibernate.model" schema="hibernatedb">
<class name="Contact" table="CONTACT">
    <id column="CONTACT_ID" length="500" name="contactID">
        <generator class="increment" />
    </id>
    <property column="GIVEN_NAME" generated="never" lazy="false" length="100" name="givenName" />
    <property column="FAMILY_NAME" generated="never" lazy="false" length="100" name="familyName" />
    <!-- one to many mapping with Action -->
    <set inverse="true" lazy="false" name="actionSet" sort="unsorted">
        <key column="CONTACT_ID" />
        <one-to-many class="com.hibernate.model.Action" />
    </set>

</class>
</hibernate-mapping>

 <hibernate-mapping package="com.hibernate.model" schema="hibernatedb">
<class name="Action" table="ACTION">
    <id column="ACTION_ID" length="500" name="actionID">
        <generator class="increment" />
    </id>
    <property column="ACTION_NOTE" type="string" name="actionNote" />
    <!-- many to one mapping with Contact -->
    <many-to-one name="contact" column="CONTACT_ID"
        class="com.hibernate.model.Contact" lazy="false" cascade="save-update" />
</class>
</hibernate-mapping>

这就是我目前尝试存储它的方式:

public class ContactServiceImpl implements ContactService{
    @Override
    public void addContacts(Contact contact) {

        contactDAO.addContact(contact);//saving the contact;
        if((contact.getActionSet()!=null)&&(contact.getActionSet().size()>0)){
            actionService.addAllActions(contact,contact.getActionSet());//saving actions, associated with the contact
        }

    }
}

看,有两个操作导致保存Actions,因为它们是Contact的属性,我相信当Contact被保存时,Actions的集合必须是也保存了。 请让我知道正确的做法。谢谢

【问题讨论】:

    标签: java spring hibernate jakarta-ee hibernate-mapping


    【解决方案1】:

    尝试设置

    &lt;set cascade="all"....

    这样,当您在联系人实体上调用保存时,休眠将保存您的操作集。

    更多详情请参阅this 回答。

    另外,请参阅the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多