简体   繁体   中英

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:

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:

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.

How do I modify the Entity classes and the JPQL query to achieve the same result as the SQL query? 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. 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. And after Googling so much, I can't find a proper guide for this ( ignoring that JPQL does not support in-line join conditions! )

You need to have a OneToOne association between the entities. And the association, on the owning side, must be annotated with @MapsId . Here's an example taken from the Hibernate documentation, which maps to your use-case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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