Batch insert entity with composite key

Viewed 982

Having these classes:

public class SomeCompositeKey implements Serializable {
    private Long objectAId;
    private Long objectBId;
    private Long objectCId;
}
//lombok annotations~~
@Entity
@Table(name = "objects_assoc")
@IdClass(SomeCompositeKey.class)
public class ObjectsAssocEntity {

    @Id
    @ManyToOne
    @JoinColumn(name = "object_a_id")
    private ObjectAEntity objectA;

    @Id
    @ManyToOne
    @JoinColumn(name = "object_b_id")
    private ObjectBEntity objectB;

    @Id
    @ManyToOne
    @JoinColumn(name = "object_c_id")
    private ObjectCEntity objectC;

}

I'm fetching references of ObjectsAssocEntity members using EntityManager.getReference() and trying to save few entities at once using saveAll method, and each time hibernate executes select to check wheter entity exists or not and then make single insert in case when it not exists.

Is there any possibility to use batch insert in this case? Or should I try to do this e.g with native query?

1 Answers

As described in docs. The spring default implementation must know if the entity is new or not.

In the case of unique primary key: It's easier for spring determine if it's new because before insert the entity id is null.

In the case of a composite key: The ID values are always filled in before persist. So in this case, for determine if the entity is new or not, you can do one of the following approachs:

  1. Use a @Version property in the entity class. For a new object, version is null. So that's enough.
  2. Implement Persistable interface
  3. Override the default spring SimpleJpaRepository EntityInformation and registering as a bean.

Suggestion: @Version has several benefits in the concurrency world. So use it.

Spring docs

Related