18

我正在尝试在我的数据库中插入数据,我在我的项目中使用 JPA。

这就是我的豆子的样子。

@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

注意:确实需要为此使用本机查询。

4

4 回答 4

14

您可以使用 NativeQuery 及其 executeUpdate 方法来完成:

String query = "insert into Employee values(1,?)";

em.createNativeQuery(query)
   .setParameter(1, "Tom")
   .executeUpdate();
于 2014-09-13T15:33:19.983 回答
9

我有同样的问题。这是解决方案。

EntityManager em = getEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
em.createNativeQuery("UPDATE ... ;").executeUpdate();
et.commit();
于 2014-06-06T10:31:30.080 回答
4
 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();
    }
于 2018-03-18T16:48:17.217 回答
3

假设您使用的是容器管理entityManager(注入@PersistenceContext),您只是错过了@TransactionnalTestFacade 方法上方的注释。

于 2013-05-29T07:31:59.973 回答