简体   繁体   中英

Hibernate automatically updating Entity1 when querying Entity2

I'm not expecting a concrete answer for this question because it's way too complex to explain in detail, just some guidance on where the problem could be.

Im summary, I have an entity Ship, with foreign keys to entities Origin, Destination and Country. I fetch a Ship from the database, then modify other field (date), and then query the database for related Origin, Destination and Country. When I query for Origin and Country, it goes as expected, but when I query for Destination, when executing query.getResultList() , and before the select a from DESTINATION , Hibernate automatically executes update SHIP set ... and it sets all the Ship fields except for IDN_DEST.

Any idea of what could this be happening?

My guess is that since the entity has been modified within the Session, Hibernates somehow things it needs to be updated, but that's all.

For what I've seen, there are no differences in the Ship.java:

// bi-directional many-to-one association
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDN_ORIGIN", insertable = false, updatable = false)
private Origin tOrigin;

@Column(name = "IDN_ORIGIN")
private Integer idnOrigin;

// bi-directional many-to-one association
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDN_DEST", insertable = false, updatable = false)
private Destination tDest;

@Column(name = "IDN_DEST", updatable = false)
private Integer idnDest;

// bi-directional many-to-one association
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDN_COUNTRY", insertable = false, updatable = false)
private Country tCountry;

@Column(name = "IDN_COUNTRY")
private Integer idnCountry;

About your question: Hibernate before a Query.list() perform a dirty check and automatically do a flush() to prevent inconsistent state.
To prevent that change Session.flushMode to COMMIT if you don't want automatic flush, but only at commit time.
About your example, two things:

  • Why you are not using a getter to get tOrigin, tCountry, tDest ?
  • May you read tOrigin, tCountry, tDest before Ship update?

Tis is happening because when you select a Destination hibernate auto-flushes the session, so the state of the Ship is updated in the database. This means that when you modify other field (date) the ship object is attached to the session.

这应该只与不能成就Destination为tibtof说,当你取从数据库它创建持久化对象的数据,当您修改hibernate会在数据库中更新它时,它刷新连接,你可以尝试是取后OriginCountry手动刷新会议您应该获取“目的地”发生的情况的最新数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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