简体   繁体   English

休眠:如何使用HQL选择空对象?

[英]Hibernate: How can I select null objects using HQL?

I have the below select statement 我有以下select语句

"SELECT new SystemUser(u.id, u.username, u.fullname, u.status, u.group.id, u.group.name, u.organization.id, u.organization.name) FROM SystemUser"

Pojo 波乔

public class SystemUser implements Serializable {

private long id;

private String username;

private String password;

private String fullname;

private SimpleStatus status;

private UserGroup group;

private Organization organization;}

and I want to select all data from SystemUser table, but rows where "SystemUser" has no "group" or "organization" are not selected. 并且我想从SystemUser表中选择所有数据,但是未选择“ SystemUser”没有“组”或“组织”的行。

How can I select all data using HQL? 如何使用HQL选择所有数据?

What you use is a constructor query select new SystemUser(...) from SystemUser . 您使用的是构造函数查询,请select new SystemUser(...) from SystemUser This will construct new objects based on the columns you select. 这将根据您选择的列构造新对象。 I think this is not necessary, you can simply write select u from SystemUser u . 我认为这不是必需的,您可以简单地select u from SystemUser u编写select u from SystemUser u

Or even simpler (but not recommended, because this is not JPQL compliant): from SystemUser 甚至更简单(但不建议这样做,因为它不符合JPQL): from SystemUser

FROM SystemUser WHERE group IS NULL OR organization IS NULL

应该工作正常。

I never try it but following the JPQL-HQL documentation I think you could do something like this (not sure if the case statement can return null values or just empty string): 我从没尝试过,但是按照JPQL-HQL文档,我认为您可以执行以下操作(不确定case语句是否可以返回空值或仅返回空字符串):

SELECT new SystemUser(
    u.id, u.username, u.fullname, u.status, 
    CASE 
        WHEN u.group IS NOT NULL THEN u.group.id
        ELSE NULL, 
    CASE 
        WHEN u.group IS NOT NULL THEN u.group.name
        ELSE NULL, 
    CASE 
        WHEN u.organization IS NOT NULL THEN u.organization.id
        ELSE NULL, 
    CASE 
        WHEN u.organization IS NOT NULL THEN u.organization.name
        ELSE NULL,
) 
FROM User u

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

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