Affects: 3.3.3.RELEASE

Currently, Spring Data JPA Repositories do not provide a method which corresponds to the single statement this.entityManager.persist(entity). There is the method save(entity), but it requires two database queries to insert an entity. Moreover, it updates an entity, if it is already in the database. We have a requirement that the insert should fail if the row is already in the database. In order to achieve this behavior, we do the following:

  1. We provide a fragment repository for the new insert(entity) method.
  2. We provide an implementation of the fragment repository. The insert-method uses the single line mentioned above: this.entityManager.persist(entity).
  3. We add the fragment repository interface from 1.) to the repository of our entity.

Since we have tens of different repositories, we had to add the fragment repository interface to many repositories---for simple, generic, often used feature: an INSERT INTO.

So, I propose to add this method to the JpaRepository.

Comment From: jnizet

Hi @ChristianWulf

I think this issue should be opened on the spring data jpa project https://jira.spring.io/projects/DATAJPA), not on spring-framework.

But anyway, some stuff to help:

  1. You can define methods in one place that automatically apply to all repositories. This is explained here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.customize-base-repository. Of course, if you add a persist() method in the base class, your interfaces will also have to extend a custom interface that also has this persist() method
  2. save() does not do 2 database operations. It checks if your entity instant is new, which by default, happens if its ID (which should be auto-generated) is null, and then calls EntityManager.persist() if that's the case. So, save(), if you use auto-generated IDs (which you should), is effectively persist(). My guess is that most of your troubles come from the fact that you don't use auto-generated IDs.

Comment From: sbrannen

Indeed, this issue should be opened in the Spring DATA JPA issue tracker.

In light of that, I am closing this issue.