我需要更好地理解休眠的这种行为,并想知道我是否可以对此事有所了解。有两个对象,Contact
并且Action
具有一对多的关系,即一个对象Contact
可以有多个Action
与之关联的对象。我想了解的是,当我存储到数据库时,如何存储 s 的集合Action
(这是 s 的一个属性)。目前我正在做的是先存储s,然后存储s。以下是我的代码:模型对象:Contact
Contact
Contact
Action
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
}
}
}
看,有两个操作导致保存Action
s,因为它们是 的属性Contact
,我相信当Contact
保存 s 时,s 的集合也Action
必须保存。请让我知道正确的做法。谢谢