我对 Hibernate 相当陌生。我试图使用下面的示例来理解 session 和事务。 我有一个事件管理系统。我有一个名为“事件”的实体,用户可以编辑事件。 我是否应该将 session 保存为服务类中的实例变量并使用它来执行多个操作 交易方式不同?我也想用它作为缓存。 session 对象应该存储在哪里?或者如何最好地实现我想做的事情 下面 - 我有两个事务 - 第一个将作为事件对象获取,第二个需要编辑它并将其保存到 数据库。
ServiceClass {
Session session ;
Constructor () {
session = sessionFactory.getSession();
}
//First transaction
public Event getEvent() {
begin new Transaction on session.
Fetch new Event object
End new transacton
return event; //to display to user
}
//Second transaction
public void editEvent(String newName, Date newDate) {
begin Transaction
Obtain the Event object from the session which was result of First transaction above
event.setName(newName); //This should be in persistent state and affect the database
event.setDate(newDate);
end Transaction
}
}
提前非常感谢:)
最佳答案
您需要将 session 视为事务。如果您的 ServiceClass 在多线程环境(例如 Servlet)中使用,那么在字段中指定它会导致线程问题。为了避免这个问题,请将 session 创建放在 editEvent() 方法中,该方法应该:
- 创建 session
- 开始交易
- 通过 session 从数据库检索实体
- 对实体进行更改
- 提交交易
关于java - 在同一 session 中使用多个事务的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918296/