我在Hibernate5中使用Spring bott 2.1.8.RELEASE。 我的问题是休眠会话的刷新方法对我不起作用。 我正在使用休眠会话的get方法从数据库中获取记录,并将其分配给其类型的某些变量。然后有30秒的暂停,与此同时,我正在从数据库级别更改该记录,并且在暂停之后,我正在调用休眠会话的刷新方法。但是此会话不会获取更改的记录,而是返回我以前使用休眠会话的get方法获取的记录。
下面是我的工作代码:
package com.example.service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.CompositeKey.Employee;
import com.example.CompositeKey.EmployeeIdentity;
@Service
public class CompositeKeyTester {
@PersistenceContext
private EntityManager entityManager;
private Session getHibernateSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
@Transactional
public void saveObjects() {
Session session = getHibernateSession();
Employee employee = session.get(Employee.class, 1);
System.out.println(employee); // return name="Rajan"
Thread.sleep(30000); // meanwhile i'm changing employee record in database, lets say name = "something"
session.refresh(employee); // I can see the database select quert executed via hinerbate logs.
System.out.println(employee); // but still getting "Rajan", It should be "something"
}
}
我通过使用两个不同的休眠会话解决了这个问题,在调用refresh方法之前,我将get方法返回的对象合并到第二个会话中。 下面是我的代码:
Session session1 = getHibernateSession();
Session session2 = getHibernateSession();
Employee employee = session1.get(Employee.class, 1);
System.out.println(employee); // return name="Rajan"
Thread.sleep(30000); // meanwhile i'm changing employee record in
database, lets say name = "something"
Employee merged = (Employee) session2.merge(employee);
session2.refresh(merged);
System.out.println(merged); // return name="something"
但是我的意思是,如何通过单个休眠会话来实现这一目标?