gpt4 book ai didi

java - Hibernate:更新不同 session 中的对象?

转载 作者:行者123 更新时间:2023-11-30 11:32:43 25 4
gpt4 key购买 nike

在 Hibernate 中,在与最初创建对象不同的 session 中更新对象是否是一种不好的做法?我认为答案是肯定的,因为 Hibernate Session(默认情况下)将缓存其 Session 对象,并在 Session 关闭或对象被逐出时释放它们。因此,在一个 session 中创建一个对象然后在另一个 session 中更新它(而对象在第一个 session 中仍然“活着”)对我来说似乎是不好的做法。任何人都可以解释为什么,有什么影响?例如,请考虑以下代码(为清楚起见已缩短):

private void updateRequest(Request req){ //Request came from another Hibernate Session
MyDAO myDB = null;
myDB = new MyDAO();
Transaction trans = myDB.getSession().beginTransaction();
myDB.getSession().update(object);
trans.commit();
}

最佳答案

这被称为“Session per operation 反模式”,这里是一个quote from hibernate documentation更好地解释了这个问题:

Do not use the session-per-operation antipattern: do not open and close a Session for every simple database call in a single thread. The same is true for database transactions. Database calls in an application are made using a planned sequence; they are grouped into atomic units of work. This also means that auto-commit after every single SQL statement is useless in an application as this mode is intended for ad-hoc SQL console work. Hibernate disables, or expects the application server to disable, auto-commit mode immediately. Database transactions are never optional. All communication with a database has to occur inside a transaction. Auto-commit behavior for reading data should be avoided, as many small transactions are unlikely to perform better than one clearly defined unit of work. The latter is also more maintainable and extensible.

关于java - Hibernate:更新不同 session 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com