我尝试使用Hibernate配置Spring Boot:
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.datalis.plugin.database.dao.TerminalsService;
import org.datalis.plugin.database.models.TerminalsModel;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Qualifier("terminalsService")
public class TerminalsDaoHibernate implements TerminalsService {
@Autowired
private EntityManager entityManager;
@Override
@Transactional
public TerminalsModel getTerminalToken(String terminalToken) throws Exception {
TerminalsModel terminal = null;
Session session = entityManager.unwrap(Session.class);
try {
entityManager.getTransaction().begin();
terminal = (TerminalsModel) session.get(TerminalsModel.class, terminalToken);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
throw new Exception("Error");
}
return terminal;
}
}
但是我遇到了这个错误:
14:47:34,323 ERROR [stderr] (default task-1) java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
14:47:34,323 ERROR [stderr] (default task-1) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
如何正确配置@Transactional注解?我需要以不同的方式使用事务吗?
entityManager.getTransaction().begin();
等操作。这正是@Transactional
已经为您做的。 - M. Deinum@Transactional
对抗(正如其名称所示,它处理您的事务)。在您的方法中,您只需要两行代码:1. 从EntityManager
获取Session
,2. 返回并从Session
获取值。(尽管我不明白为什么需要这个Session
)。 - M. Deinum