英文:
Batch insert entity with composite key
问题
以下是翻译好的内容:
拥有以下类:
public class SomeCompositeKey implements Serializable {
private Long objectAId;
private Long objectBId;
private Long objectCId;
}
// Lombok注解~~
@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;
}
我正在使用EntityManager.getReference()
来获取ObjectsAssocEntity
成员的引用,并尝试使用saveAll
方法一次性保存多个实体,每次Hibernate都会执行选择以检查实体是否存在,然后在实体不存在时进行单个插入。
在这种情况下,是否有可能使用批量插入?还是我应该尝试使用原生查询来实现?
英文:
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
得分: 5
如文档所述。Spring的默认实现必须知道实体是新的还是旧的。
对于具有唯一主键的情况:对于Spring来说,更容易判断是否是新实体,因为在插入之前实体ID为null。
对于复合主键的情况:ID值总是在持久化之前填充好的。所以在这种情况下,要判断实体是新的还是旧的,可以采取以下其中一种方法:
- 在实体类中使用 @Version 属性。对于新对象,版本为null。因此这就足够了。
- 实现 Persistable 接口
- 覆盖默认的 Spring SimpleJpaRepository EntityInformation 并将其注册为一个bean。
建议:@Version 在并发世界中有几个优点。所以建议使用它。
英文:
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:
- Use a @Version property in the entity class. For a new object, version is null. So that's enough.
- Implement Persistable interface
- Override the default spring SimpleJpaRepository EntityInformation and registering as a bean.
Suggestion: @Version has several benefits in the concurrency world. So use it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论