我正在尝试在我的数据库中插入数据,我在我的项目中使用 JPA。
这就是我的 Bean 的样子。
@PersistenceContext
EntityManager em;
em.createNativeQuery("INSERT INTO testtable ('column1','column2') VALUES ('test1','test2')").executeUpdate();
我的外观:
@Stateless
public class TestFacade extends AbstractFacade<Test> {
@PersistenceContext(unitName = "TEST2PU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public TestFacade() {
super(Test.class);
}
我收到一个错误:
javax.persistence.TransactionRequiredException: executeUpdate is not supported for a Query object obtained through non-transactional access of a container-managed transactional EntityManager
如果我不使用@PersistenceContext for EntityManager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("TEST2PU");
EntityManager em = emf.createEntityManager();
em.createNativeQuery("INSERT INTO testtable ('column1','column2') VALUES ('test1','test2')").executeUpdate();
这是我的错误:
javax.persistence.TransactionRequiredException:
Exception Description: No externally managed transaction is currently active for this thread
注意:确实需要为此使用 native 查询。
最佳答案
您可以使用 NativeQuery 及其executeUpdate 方法来完成此操作:
String query = "insert into Employee values(1,?)";
em.createNativeQuery(query)
.setParameter(1, "Tom")
.executeUpdate();
关于jpa - 使用实体管理器 native 查询插入我的 JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805224/