简体   繁体   English

使用 JPA 查询可为空的 @OneToOne 关系

[英]Querying a nullable @OneToOne relationship with JPA

I have Entity1 and Entity2 .我有Entity1Entity2 They have a OneToOne nullable relationship.它们具有 OneToOne 可为空的关系。

@Entity
class Entity1 {

   @Id
   @Column(name = "id")
   private Long id;

   @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "entity2")
   @JoinColumn(nullable = true)    
   private Entity2 entity2;
   ...
}

How can I query all Entity1 objects that has a null entity2 ?如何查询所有具有空entity2 Entity1对象?

Because if I do:因为如果我这样做:

SELECT e FROM Entity1 e WHERE e.entity2 IS NULL

JPA engine do a JOIN between the two tables and put a useless WHERE clausule ( WHERE entity_id = NULL ). JPA 引擎在两个表之间执行 JOIN 并放置一个无用的 WHERE 子句( WHERE entity_id = NULL )。 Resuming, it executes an useless native SQL.继续,它执行一个无用的本机 SQL。 How can怎么能

Current solution:当前解决方案:

Reading the OpenJPA documentation, I found that Native Queries should be used to workaround JPA limitations.阅读 OpenJPA 文档,我发现应该使用 Native Queries 来解决 JPA 限制。 I can get it very easy using native query and I'm currently doing it, but I would like to avoid to use it.我可以很容易地使用本机查询,我目前正在这样做,但我想避免使用它。

You can simply run this JPQL query:你可以简单地运行这个 JPQL 查询:

SELECT e1 
FROM Entity1 e1 
LEFT JOIN e1.entity2 e2
WHERE e2 IS NULL

The LEFT JOIN is what you were looking for. LEFT JOIN正是您要找的。

Yes it can be done without performing join and using JPA query.是的,它可以在不执行连接和使用 JPA 查询的情况下完成。 Check out the following code snippet:查看以下代码片段:

@Entity
class Entity1 {
   ...
   @OneToOne(...)
   @JoinColumn(name="entity2ID")
   private Entity2 entity2;
   @Column(name="entity2ID", nullable=true, insertable=true, updatable=true)
   private Long entity2ID;
   ...
}

Simply map the joining column in entity as insertable/updatable as FALSE.只需将实体中的连接列映射为可插入/可更新为 FALSE。 The Make sure that you absolutely not provide setter method for xyz or joining column.确保您绝对没有为 xyz 或连接列提供 setter 方法。 Once this is done you can use following query:完成此操作后,您可以使用以下查询:

SELECT e FROM Entity1 e WHERE e.entity2ID IS NULL

This won't perform any joins as you are querying for joining column directly.当您直接查询连接列时,这不会执行任何连接。

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

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