使用JPA查询可为空的@OneToOne关系 [英] Querying a nullable @OneToOne relationship with JPA

查看:173
本文介绍了使用JPA查询可为空的@OneToOne关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Entity1 Entity2 .他们有一个OneToOne可为空的关系.

I have Entity1 and Entity2. They have a OneToOne nullable relationship.

@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;
   ...
}

如何查询所有 entity2 为空的 Entity1 对象?

How can I query all Entity1 objects that has a null entity2?

因为我这样做:

SELECT e FROM Entity1 e WHERE e.entity2 IS NULL

JPA引擎在两个表之间进行JOIN并放置无用的WHERE子句( WHERE entity_id = NULL ).继续执行无用的本机SQL.

JPA engine do a JOIN between the two tables and put a useless WHERE clausule (WHERE entity_id = NULL). Resuming, it executes an useless native SQL. How can

当前解决方案:

阅读OpenJPA文档后,我发现应使用本机查询来解决JPA限制.使用本机查询可以很容易地完成它,而我目前正在这样做,但我想避免使用它.

Reading the OpenJPA documentation, I found that Native Queries should be used to workaround JPA limitations. I can get it very easy using native query and I'm currently doing it, but I would like to avoid to use it.

推荐答案

您可以简单地运行以下JPQL查询:

You can simply run this JPQL query:

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

您正在寻找 LEFT JOIN .

这篇关于使用JPA查询可为空的@OneToOne关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆