I want do use JPA Batches in my code.
I am using this Dependencies:
<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>
Do I have to add sth in my persistence.xml file? If yes, what do I have to add?
This is how I wrte the Jobs in my DB at the moment:
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();
}
After 100 Joby my program wirtes the values in the DB so that is not every time a DB access.
------------------------------ EDIT -----------------------------------
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();
}
Then I get the: java.lang.NullPointerException
------------------------------ EDIT 2 -----------------------------------
I got the NPE in the line
final java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
But how do I solve this problem?
CodePudding user response:
You can unwrap the EntityManager to a java.sql.Connection: java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
Then you can use PreparedStatements as in this answer: Efficient way to do batch INSERTS with JDBC