如何在 EclipseLink 中执行 JPA 批处理(插入)

How do I do JPA Batches (Insert) in EclipseLink

我想在我的代码中使用 JPA 批处理。

我正在使用这个依赖项:

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0-RC1</version>
        </dependency>

我必须在 persistence.xml 文件中添加某物吗?如果是,我还需要补充什么?

这就是我目前在数据库中编写作业的方式:

    public void writeAllJobs(List<Jobs> jobs) {

        final EntityManager em = factory.createEntityManager();

        em.getTransaction().begin();

        int counter= 0;

        for (final Job j : jobs) {

            if (counter++ >= 100) {
                em.getTransaction().commit();
                em.getTransaction().begin();
                counter = 0;
            }

            final Job job = new Job();
            job.setJobkey(j.getJobkey());
            job.setDescription(b.getDescription());
            em.persist(job);
        }
        em.getTransaction().commit();

        em.close();
    }

在 100 个 Joby 之后,我的程序将值写入数据库中,这样就不会每次都访问数据库了。

----------------------------编辑-------- --------------------------

    public void writeAllJobs(List<Jobs> jobs) throws SQLException {

        final EntityManager em = factory.createEntityManager();
        final java.sql.Connection connection = em.unwrap(java.sql.Connection.class);

        final String compiledQuery = "INSERT INTO JOB(JOBKEY ,DESCRIPTION)" + " VALUES" + "(?, ?)";
        final PreparedStatement preparedStatement = connection.prepareStatement(compiledQuery);

        for (final Job j : jobs) {
            preparedStatement.setInt(1, j.getJobkey());
            preparedStatement.setString(2, j.getDescription());

            preparedStatement.addBatch();
        }

        preparedStatement.executeBatch();

        connection.close();
    }

然后我得到:java.lang.NullPointerException

---------------------------- 编辑 2 ------ --------------------------

我在行中得到了 NPE
final java.sql.Connection connection = em.unwrap(java.sql.Connection.class);

但是我该如何解决这个问题呢?

您可以将 EntityManager 解包为 java.sql.Connection:java.sql.Connection connection = em.unwrap(java.sql.Connection.class);

然后你可以像这个答案一样使用 PreparedStatements:Efficient way to do batch INSERTS with JDBC