简体   繁体   English

JPQL Left Join - 如何在实体类中设置实体关系

[英]JPQL Left Join - how to set up entity relationship in entity classes

Two tables: 两张桌子:

TABLE_1:
REC_ID
1
2
3
4

TABLE_2:
REC_ID REC_VAL
2      A
3      B

Entity classes (basic structure): 实体类(基本结构):

@Entity
@Table(name="TABLE_1")
public class Entity1 {
    @Id
    @Column(name="REC_ID")
    private String recId;

    //getters and setters
}

@Entity
@Table(name="TABLE_2")
public class Entity2 {
    @Id
    @Column(name="REC_ID")
    private String recId;

    @Column(name="REC_VAL")
    private String recVal;

    //getters and setters
}

SQL Query and result: SQL查询和结果:

SELECT T1.REC_ID, T2.REC_VAL FROM TABLE_1 T1 LEFT OUTER JOIN TABLE_2 T2 ON T1.REC_ID = T2.RED_ID

Result:
REC_ID REC_VAL
1      null
2      A
3      B
4      null

JPQL Query: JPQL查询:

SELECT e1.recId, e2.recVal FROM Entity1 e1 LEFT JOIN e1.<an Entity2 field in Entity1*>

* I know I don't have it in the given structure above, but I want to know how to do it right. *我知道我在上面给定的结构中没有它,但我想知道如何正确地做到这一点。 And how do I choose from @ManyToOne, @OneToOne, etc. 我如何选择@ManyToOne,@ OneToOne等。

How do I modify the Entity classes and the JPQL query to achieve the same result as the SQL query? 如何修改Entity类和JPQL查询以获得与SQL查询相同的结果? I've been trying various things, nothing works. 我一直在尝试各种各样的事情,没有任何作用。 It wouldn't allow me to create two fields with the same column name, or to define the String as the @JoinColumn. 它不允许我创建具有相同列名的两个字段,或者将String定义为@JoinColumn。 I almost got it working, but the generated SQL query contains a reference to REC_ID_REC_ID column in TABLE_2 which doesn't exist. 我几乎让它工作,但生成的SQL查询包含对TABLE_2中REC_ID_REC_ID列的引用,该列不存在。 And after Googling so much, I can't find a proper guide for this ( ignoring that JPQL does not support in-line join conditions! ) 在Googling这么多之后,我找不到合适的指南( 忽略JPQL不支持内联连接条件!

You need to have a OneToOne association between the entities. 您需要在实体之间建立OneToOne关联。 And the association, on the owning side, must be annotated with @MapsId . 而且,在拥有方面,关联必须使用@MapsId进行注释。 Here's an example taken from the Hibernate documentation, which maps to your use-case: 以下是从Hibernate文档中获取的示例,该文档映射到您的用例:

@Entity
public class Body {
    @Id
    public Long getId() { return id; }

    @OneToOne(cascade = CascadeType.ALL)
    @MapsId
    public Heart getHeart() {
        return heart;
    }
    ...
}   

@Entity
public class Heart {
    @Id
    public Long getId() { ...}
}          

Once you have that, you can use a query such as 完成后,您可以使用诸如的查询

select b.foo, h.bar from Body b left join b.heart h where ...

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

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