我正在尝试在我的数据库中插入数据,我在我的项目中使用JPA。
这就是我的bean的样子。
@PersistenceContext
EntityManager em;
em.createNativeQuery("INSERT INTO testtable ('column1','column2') VALUES ('test1','test2')").executeUpdate();myfacade:
@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注意:确实需要使用原生查询来实现这一点。
发布于 2014-09-13 23:33:20
您可以使用NativeQuery及其executeUpdate方法来完成此操作:
String query = "insert into Employee values(1,?)";
em.createNativeQuery(query)
.setParameter(1, "Tom")
.executeUpdate();发布于 2014-06-06 18:31:30
我也有同样的问题。以下是解决方案。
EntityManager em = getEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
em.createNativeQuery("UPDATE ... ;").executeUpdate();
et.commit();发布于 2018-03-19 00:48:17
String message = "";
try
{
EntityManager em = emf.createEntityManager();
if (objUser.getId() <= 0)
{
em.getTransaction().begin();
em.createNativeQuery("INSERT INTO userinfo ( login, upassword, email, mobile, fax, dob)"
+ " VALUES ( :a, :b, :c, :d, :e, :f)")
.setParameter("a", objUser.getLogin())
.setParameter("b", objUser.getUpassword())
.setParameter("c", objUser.getEmail())
.setParameter("d", objUser.getMobile())
.setParameter("e", objUser.getFax())
.setParameter("f", objUser.getDob()).executeUpdate();
em.getTransaction().commit();
em.close();
message = "Success";
}
} catch (HibernateException ex)
{
message = ex.getMessage();
}https://stackoverflow.com/questions/16805224
复制相似问题