jpa - 使用实体管理器 native 查询插入我的 JPA

标签 jpa entitymanager

我正在尝试在我的数据库中插入数据,我在我的项目中使用 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/

相关文章:

java - 如何在不定义主键字段的情况下使用实体管理器插入记录?

hibernate - 使用本地时区存储的日期 - Hibernate JPA

java - MySQL 中的 JPA 唯一索引创建失败

java - org.hibernate.AnnotationException : Unable to create unique key constraint

java - 尝试在 jpa 表上创建新条目时出错

mysql - 连接服务器上的数据库的最佳方法是什么?

java - 如何在JPQL中随机选择10条记录?

java - 使用 dao 接口(interface)和实现实现通用抽象实体类

java - 在循环中运行 nativeQuery 不会返回正确的数据

JPA EntityManager 为什么merge() 不管理实例?