[英]Hibernate automatic save after Transaction
This is my hibernate relationship 这是我的冬眠关系
@OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "b_id", nullable = false)
@XmlElement
@JsonIgnore
@Getter
@Setter
private List<A> aList = new ArrayList<>();
@ManyToOne
@JoinColumn(name = "b_id", nullable = false, insertable = false, updatable = false)
@XmlTransient
@Getter
@Setter
private B b;
So would be like I call method x, there I´m get from database entity B then I set new aList with all A with id null, into B and then I return B in the method but I´m not saving B in any moment. 因此,就像我调用方法x一样,我从数据库实体B中获取信息,然后将ID为null的所有A都设置为新的aList到B中,然后在该方法中返回B但我在任何时候都不保存B 。 When I see the value of the aList inside B this A of the aList already have ids!!!, so in some point the B is save in database and aList is done on cascade.
当我在B内看到aList的值时,这个aList的A已经有ids !!!,因此在某些时候B会保存在数据库中,而aList是级联完成的。 The thing is that I´m calling this method inside @Service class from my Controller, so I´m thinking that because the transaction is finish, Hibernate detect a change into the B and decide to persist the changes.
事实是,我正在从Controller的@Service类中调用此方法,所以我认为由于事务已完成,因此Hibernate会检测到B中的更改并决定保留更改。 The question would be, how avoid that behavior!!!
问题是,如何避免这种行为!!!
Object in session cache will be synchronized with database on Session.flush()
, including relations as you are using CascadeType.ALL
. 会话缓存中的对象将与
Session.flush()
上的数据库同步,包括使用CascadeType.ALL
关系。
If you want to avoid the synchronization on some object, you can use the Session.evict(someObject)
method before the transaction commit. 如果要避免在某些对象上同步,则可以在提交事务之前使用
Session.evict(someObject)
方法。
我找到了解决方案,忘了说我在使用Spring,所以最后我将@Transactional(readOnly = true)添加到我的方法中,而不是在服务类级别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.