1

I currently a spring boot project with postgres and hibernate and had the following functions:

  private fun savePost(post: Post): Post = entityManager.merge(post)

  private fun savePosts(posts: List<Post>) = 
       posts.forEach { save(post) }

I wanted to avoid a sequential insert so now I have a raw query:

 private fun savePosts(posts: List<Post>) {
      val queryText: String = createTextQueryFromList(posts)
      val query = entityManager.createNativeQuery(queryText)
      query.executeUpdate()
 }

This does work but it is not very clean.

What is the correct way for a bulk insert using criteria builder?

Jon Doe
  • 23
  • 5

1 Answers1

0

The first option would be to iterate over the posts and flush a batch of updates and release memory. The last answer here: Batch inserts using JPA EntityManager says JPA by itself does not have any settings for batching. However there are some implementation-dependent settings. Here is an example for hibernate. See 13.2. Batch updates

The other option would be to try session.doWork() See example https://keyurj.blogspot.com/2012/12/dowork-in-hibernate.html

fhery021
  • 317
  • 2
  • 7
  • Hello, The answer you provided me with applies to JPA repositories. I don't have any repositories (classes which implement the JPA repository interface) and instead, am utilizing an entity manager. Could you please elaborate on how I can apply the suggested scenario to my case? – Jon Doe Jan 07 '19 at 00:57