简体   繁体   English

休眠保存/更新级联

[英]Hibernate Save/Update Cascade

There is a class A like: 有一个类A:

class A {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Basic(optional = false)
     @Column(name = "DBId")
     private Long DBId = null;

     @OneToMany(cascade = CascadeType.ALL)
     @LazyCollection(LazyCollectionOption.FALSE)
     List<B> list;
}

and a class B like 和B级一样

class B {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Basic(optional = false)
     @Column(name = "DBId")
     private Long DBId = null;
}

When I want to persist a new instance of class A, two cases are possible. 当我想要持久化A类的新实例时,有两种情况是可能的。 1- All instances of B in A are new, in which case, a simple session.save(A) is ok. 1- A中B的所有实例都是新的,在这种情况下,一个简单的session.save(A)就可以了。 2- Some or all of the instances of B in A are old. 2- A中B的部分或全部实例都是旧的。 How should I save A in order not to have duplicate Bs. 如何保存A以便不会有重复的Bs。 Will saveOrUpdate solve the problem? saveOrUpdate会解决问题吗? or it will just decide to choose save or update just by looking at A, and for example if A was new, it will also call save on Bs, and if A was old, it will also call update on Bs? 或者只是通过查看A来决定选择保存或更新,例如,如果A是新的,它也会调用B上的保存,如果A是旧的,它还会调用Bs上的更新?

Furthermore, I saw that I had just a simple session.save(A) in my codes, and it did not produce redundant Bs. 此外,我看到我的代码中只有一个简单的session.save(A),并且它没有产生冗余的Bs。 Am I wrong? 我错了吗? Is this possible? 这可能吗?

Regards 问候

UPDATE: in case of old Bs, the instances of old Bs are attached to the session, and DBId is correctly set. 更新:在旧B的情况下,旧B的实例附加到会话,并正确设置DBId。

Do your entities live longer than sessions? 您的实体比会话更长寿吗? If not, you don't have to use update() or saveOrUpdate() . 如果没有,则不必使用update()saveOrUpdate() When you call session.save() , Hibernate knows whether to insert or update , by checking the state of the entity. 当你调用session.save() ,Hibernate通过检查实体的状态来知道是insert还是update You can read here for more about states: http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#objectstate-overview 你可以在这里阅读有关各州的更多信息: http//docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#objectstate-overview

The same applies to the cascade. 这同样适用于级联。 When the operation is cascaded to the collection, Hibernate will check the state of the entities in the collection and will NOT try to insert them, if they are already in PERSISTENT state. 当操作级联到集合时,Hibernate将检查集合中实体的状态,如果它们已处于PERSISTENT状态,则不会尝试插入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM