简体   繁体   English

交易后休眠自动保存

[英]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.

相关问题 Hibernate save()和事务回滚 - Hibernate save() and transaction rollback Hibernate在同一事务中新创建的记录上的save()之后调用get() - Hibernate calling get() after save() on the newly created record within the same transaction 在上一个事务失败后,hibernate / spring尝试插入而不是保存(db中的记录已存在) - hibernate/spring is trying to insert rather than save (record already exists in db) after the previous transaction failed Hibernate 保存后插入 - Hibernate insert after save 休眠-在没有活动事务的情况下保存无效 - Hibernate - save is not valid without active transaction Spring MVC和Hibernate应该按需保存事务 - spring mvc and hibernate should save the transaction on demand Hibernate Save()-&#39;Save Method&#39;是什么意思,save()在事务之外工作? - Hibernate Save() - 'Save Method' what is it mean by save() work outside the transaction? 事务提交后,休眠线程未完成 - Hibernate thread do not finish after transaction commits 事务插入后,Hibernate检索旧数据 - Hibernate retrieves OLD data after transaction insert org.hibernate.HibernateException:迁移到Hibernate 5后,当前事务未在进行中 - org.hibernate.HibernateException: Current transaction is not in progress after migrate to Hibernate 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM