JPQL 右连接

pis*_*ise 5 hibernate jpql jpa-2.0 right-join

经过搜索,我才知道 JPQL 中没有 Right Join。我看到有另一种方法可以使用 JPA 双向(不是右连接,而是使用 pojo 对象)来实现它,但是我在控制台中注意到一件事,它对数据库进行了多次调用,例如见下表。

       Flat Table                   UserToFlat                    User
| Flat_ID  |  Flat No  |      | ID   |  Flat_ID | User_ID |    | User_ID | Name |
|  1       |    101    |      | 1    |    1     |  1      |    |   1     | XYZ  |  
|  2       |    102    |      | 2    |    2     |  2      |    |   2     | PQR  |
|  3       |    103    |      | 3    |    3     |  3      |    |   3     | ABC  |
|  4       |    104    |
Run Code Online (Sandbox Code Playgroud)

我想要平面表中的所有行,并且只需要用户表中的匹配行

// below query do not work as flat is having primary key and usertoflat having foreign key
select f, u from FlatEntity f left join f.userToFlatEntity uf join uf.user u;

// now if I try right join then jpql throws exception
select f from UserToFlatEntity uf right join uf.flatEntity f;
Run Code Online (Sandbox Code Playgroud)

现在,如果我使用 jpql birectional 并使用对象获取例如

// suppose I have FlatEntity Object 
flatEntity.getUserToFlatEntity();
Run Code Online (Sandbox Code Playgroud)

上面的代码将在条件 flat_ID = ? (在这种情况下是 4 次),我认为这不是很好的表现。

那么有什么方法可以让 JPQL 在不影响性能的情况下实现正确连接。

实体配置

public class FlatEntity {
    @OneToOne(mappedBy = "flatEntity")
    private UserToFlatEntity userToFlatEntity;

   // getter setter
}

public class UserToFlatEntity {
    @ManyToOne
    @JoinColumn(name = "flatId", insertable = false, updatable = false)
    private FlatEntity flatEntity;
}

public class UserEntity {
    @OneToMany(mappedBy = "userEntity")
    private Set<UserToFlatEntity> userToFlatEntitySet;
}

Exception
 Path expected for join!
 at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromJoinElement(HqlSqlWalker.java:369)
Run Code Online (Sandbox Code Playgroud)

Har*_*had 5

您应该使平面表成为关系的所有者方(在我看来,这更符合逻辑)。然后您可以使用 LEFT JOIN 而不是 RIGHT JOIN。

SELECT uc, MAX(ua.accessTs) FROM Flat Table uc LEFT JOIN uc.User Table ua
Run Code Online (Sandbox Code Playgroud)

以下是 UserTable 上的左连接有效的原因:

有关更多详细信息,请访问此处:JPQL 中的 RIGHT JOIN

在此输入图像描述