简体   繁体   English

在单个查询中使用FK更新现有的JPA子实体

[英]Updating existing JPA child entities with FK in a single query

I have a parent/child one-to-many unidirectional relation. 我有一个父母/孩子一对多的单向关系。 Both the parent and the child POJOs use custom Insert-on-duplicate-update insert queries specified via @SQLInsert annotation. 父POJO和子POJO均使用通过@SQLInsert批注指定的自定义重复插入更新查询。

Parent/child pair is inserted via cascading - everything works fine and the entity manager is closed. 通过级联插入父/子对-一切正常,并且关闭实体管理器。 Then I create a new entity manager and try to insert the same parent/child pair, but with updated values (same primary keys, but some of the other fields are changed). 然后,我创建一个新的实体管理器,并尝试插入相同的父/子对,但是具有更新的值(相同的主键,但其他一些字段已更改)。

The parent's Insert-on-duplicate-update works just fine and the values are updated. 父级的“ 重复插入”工作正常,并且值已更新。 In the child table however we end up with 2 entries, one with the old values and NULL parent_id foreign key, and one with the new values and correctly set FK. 但是,在子表中,我们最终得到2个条目,一个具有旧值和NULL parent_id外键,一个具有新值并正确设置FK。

I looked at the queries generated by Hibernate and found out the following: 我查看了Hibernate生成的查询,发现了以下内容:

  • The child row is inserted with the foreign key set to NULL 插入子行并将外键设置为NULL
  • Then an update query is ran that sets the parent_id for the given child id 然后运行更新查询,该查询为给定的子ID设置parent_id
  • Another update is ran that sets the parent_id to NULL, I'm assuming for the child id of the first row 运行了另一个更新,将parent_id设置为NULL,我假设第一行的子ID
  • A third update query is ran that sets the parent_id 运行第三个更新查询,该查询设置了parent_id

Is there a way for cascading insert to insert the child row and set the FK in the same query, thus eliminating the need for running a separate update query? 是否可以通过级联插入来插入子行并在同一查询中设置FK,从而消除了运行单独的更新查询的需要?

The question was answered as a part of a different question of mine: JPA insert parent/child results in MySQLIntegrityConstraintViolationException 这个问题是我的另一个问题的一部分: JPA在MySQLIntegrityConstraintViolationException中插入父/子结果

Basically, you have to set nullable = false in the @JoinColumn that specifies creates the parent/child relation. 基本上,您必须在@JoinColumn中将nullable = false设置nullable = false指定创建父/子关系。

There still seems to be an update query running for some reason but the complete record is being inserted with the insert statement. 出于某种原因,似乎仍在运行更新查询,但是完整的记录正在通过insert语句插入。

The accepted answer did not solve my problem. 接受的答案不能解决我的问题。

Adding updatable=false to the parent entity solved it. 向父实体添加updatable = false可以解决该问题。 JPA does not execute the update query. JPA不执行更新查询。 However, I have no clue why that's the case and in fact, I don't think what I am doing is correct because it means I cannot update the child table later on if I have to. 但是,我不知道为什么会这样,实际上,我不认为我在做什么是正确的,因为这意味着以后如果必须的话,我无法更新子表。

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

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