简体   繁体   English

OneToOne的mappedBy表现怪异

[英]OneToOne's mappedBy behaves weird

Why is that a bidirectional OneToOne relationship behaves a bit weird in the following case?: 为什么在以下情况下双向OneToOne关系的行为OneToOne

  1. I create 2 owner side entities with the same inverse side entity 我用相同的反面实体创建2个拥有者面实体
  2. With another run of the application, I find the second owner side entity (with EntityManager ), and then reach the inverse side object 在应用程序的另一次运行中, 我找到了第二个所有者方实体(使用EntityManager ), 然后到达逆向对象
  3. And at this point if I reach the owner object through the inverse side object's reference, I get the first owner (attached picture helps) 而在这一点上,如果我通过反面对象的引用到达所有者对象,那么我将获得第一个所有者(附加图片有帮助)

在此处输入图片说明

The entities are nothing special: 实体没什么特别的:

  • Employee contains: 员工包含:

    @OneToOne(cascade = CascadeType.ALL) private Person person;

  • while Person contains: 而“人”包含:

    @OneToOne(mappedBy="person") private Employee employee;

It seems confusing for me, misleading. 对于我来说,这似乎令人困惑,具有误导性。 Is this a bug maybe, or the programmer has to know about their possibilities? 这可能是一个错误,还是程序员必须了解它们的可能性?

Why do you reuse the same Person for two different employees? 您为什么要为两个不同的员工重用同一Person This is not a OneToOne relationship anymore. 这不再是OneToOne关系。

Btw what I suspect happens in the back, Hibernate executes the following query: 顺便说一句,我怀疑背后发生了什么,Hibernate执行以下查询:

 SELECT e FROM employee e WHERE person_id = ?

In this case the result set will contain two rows and Hibernate will use the first one only, of course the ordering is undefined in this case (depending on the DB you are using). 在这种情况下,结果集将包含两行,而Hibernate将仅使用第一行,当然,在这种情况下,顺序是不确定的(取决于您使用的数据库)。

You can double check this by enabling SQL logging. 您可以通过启用SQL日志记录再次检查。

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

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