RIGHT JOIN in JPQL

做~自己de王妃 提交于 2019-12-04 00:55:36

问题


I have the following JPA entities:

@Entity
class UserClient{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
}

@Entity
class UserAccess{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToOne(optional = false, cascade = { CascadeType.REFRESH })
    private UserClient user;

    @Temporal(TemporalType.TIMESTAMP)
    private Date accessTs;
}

Now I wanted to run a JPQL query to get the list of the users with their last access date. Unfortunately the following query doesn't return the users that never accessed the system, i.e exist in UserClient table, but don't have any record in UserAccess one.

SELECT ua.user, MAX(ua.accessTs) FROM UserAccess ua RIGHT JOIN ua.user

Do I miss something? Is that correct use of RIGHT JOIN?

I'm using the latest Hibernate JPA release (4.0.0.CR1)


回答1:


You should make the UserClient table the owner side of the relationship (which make more logical sense IMO). Then you can use a LEFT JOIN instead of a RIGHT JOIN.

SELECT uc, MAX(ua.accessTs) FROM UserClient uc LEFT JOIN uc.userAccess ua

Here's why left join on UserAccess works:



来源:https://stackoverflow.com/questions/7210269/right-join-in-jpql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!