简体   繁体   English

Spring JPA 生成 SELECT 查询现有拥有实体的新关联实体

[英]Spring JPA generates SELECT query for new associated entities of existing owning entity

I have an owning entity class with some associated entities, eg我有一个拥有实体 class 和一些关联实体,例如

@Entity
public class Parent {
    @Id
    @GeneratedValue
    private UUID id;
    @OneToMany(mappedBy = "parentId", cascade = CascadeType.ALL)
    List<Child> children;
    ...
}

@Entity
public class Child {
    @Id
    @GeneratedValue
    private UUID id;
    private UUID parentId;
    ...
}

I am using Spring Boot Starter Data JPA. I traced the code to the SimpleJpaRepository class, I noticed that on calling save(parent) , it checks if isNew() returns true, Spring will call persist() ;我正在使用 Spring Boot Starter Data JPA。我将代码追踪到SimpleJpaRepository class,我注意到在调用save(parent)时,它会检查 isNew isNew()是否返回 true,Spring 将调用persist() otherwise it calls merge() .否则它调用merge() This makes total sense, as persist() will generate only an INSERT, while merge() will generate a SELECT (if it hasn't done before) and then followed by an INSERT if the SELECT returns nothing;这是完全有道理的,因为persist()将只生成一个 INSERT,而merge()将生成一个 SELECT(如果之前没有完成),然后如果 SELECT 没有返回任何内容,则紧接着是一个 INSERT; otherwise an UPDATE.否则更新。

The above works well when saving a new Parent with new Child , only INSERTs are generated without any SELECT.当用新的Child保存新的Parent时,上面的方法很好用,只生成 INSERTs 而没有任何 SELECT。

However, my problem is, when creating some new Child and adding them to an existing Parent , then on saving the parent, somehow I noticed Spring JPA is still generating an extra SELECT for each of these new Child entities before the INSERTs, which I found unnecessary.但是,我的问题是,当创建一些新的Child并将它们添加到现有的Parent ,然后在保存父级时,我注意到 Spring JPA 仍然为我发现的 INSERT 之前的每个新Child实体生成额外的 SELECT不必要。

Is there a way to avoid these SELECT queries?有没有办法避免这些 SELECT 查询?


Further investigation I found that if I leave the id of the Child null (ie let it auto generates a new id), then only INSERT is generated.进一步调查我发现,如果我保留Childid null(即让它自动生成一个新的 id),那么只会生成 INSERT。 However, if I manually assign an id to a Child , then a SELECT will be generated before an INSERT.但是,如果我手动将 id 分配给Child ,则将在 INSERT 之前生成 SELECT。 Is there a way I can assign id to Child while avoiding the extra SELECT?有没有一种方法可以在避免额外的 SELECT 的同时将 id 分配给Child

On the basis of your code i think because of .netoMany mapping and you did't provide cascade type then it not happen select query running two times provide more information full code of Entity classes properties file根据您的代码,我认为是因为 .netoMany 映射并且您没有提供级联类型,所以它不会发生 select 查询运行两次提供更多信息实体类属性文件的完整代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM