通过以下Dao类中的注释配置获取EntityManager的实例。在Rest API中使用的Dao类如下。第一次调用save dao方法时,新的UserEntity('name-1','password-1')保存在数据库中,但是当调用第二个save方法(userDao.save(new UserEntity('name-2','password- 2'))),通过消息“ java.lang.IllegalStateException:Session / EntityManager已关闭”发生了异常。
public class REST {
@Autowire
DaoUser userDao;
public void save(){
userDao.save(new UserEntity('name-1', 'password-1'));
userDao.save(new UserEntity('name-2', 'password-2'));
}
}
class UserDao {
@PersistenceContext(
name = "stadto",
type = PersistenceContextType.TRANSACTION
)
private EntityManager manager;
public void save(UserEntity user){
Session session = manager.unwrap(Session.class);
Transaction transaction = session.getTransaction();
transaction.beginTransaction();
session.save(user);
transaction.commit();
session.close();
}
}