使用可能为null的对象值在hibernate中对集合进行排序

时间:2014-09-24 05:37:43

标签: java hibernate sorting collections

我有一个像这样的hibernate类:

public class UserActivityLog implements java.io.Serializable {

private static final long serialVersionUID = 1L;
private Integer id;
private Users users;
private Servers servers;
private Date time;
private String event;
}

我使用hibernate排序对UserActivityLog对象进行排序。这是我的休眠标准:

    criteria.add(Restrictions.ge(sortField, new Timestamp(startDate.getTime())));
    //add one day to the real end date for it to be considered in criteria
    Date eDate = getEndDate(endDate);
    criteria.add(Restrictions.le(sortField, new Timestamp(eDate.getTime())));
    if (searchByUser >= 0) {
        criteria.add(Restrictions.eq("users.id", searchByUser));
    }
    if (searchByHostId >= 0) {
        criteria.add(Restrictions.eq("servers.id", searchByHostId));
    }
    if (!searchByEvent.isEmpty()) {
        criteria.add(Restrictions.like("event", searchByEvent, MatchMode.ANYWHERE));
    }


    if(sortColumn.equals("username")) {
        sortColumn = "users.username";
        criteria.createAlias("users", "users");
    }
    else if (sortColumn.equals("hostName")) {
        sortColumn = "servers.hostName";
        criteria.createAlias("servers", "servers");
    }
    //specify the sorting oder
    if(SortDirection.asc.equals(sortDirection)) {
        criteria.addOrder(Order.asc(sortColumn));
    } else {
        criteria.addOrder(Order.desc(sortColumn));
    }

    List<Object> allRows = (ArrayList<Object>) criteria.list();

UserActivityLog的servers属性可以为null。当集合具有服务器为null的对象时,如果我使用hostName(即Servers对象中的属性)对集合进行排序,则已排序的集合不包含具有servers = null的对象。是否有任何理由或我做错了什么?

更新: 这是hibernate查询:

select count(*) as y0_ from USER_ACTIVITY_LOG this_ inner join SERVERS servers1_ on    this_.HOST_ID=servers1_.ID 
where this_.TIME>='2014/9/16' and this_.TIME<='2014/9/25' order by servers1_.HOST_NAME asc

2 个答案:

答案 0 :(得分:0)

我猜想由于以下原因,未从数据库中提取带有servers = null的对象:

if (searchByHostId >= 0) {
    criteria.add(Restrictions.eq("servers.id", searchByHostId));
}

不是因为那种。

答案 1 :(得分:0)

我找到了根本原因和解决方案: 当我检查对应于此排序的hibernate查询时,它具有与Servers表的内部联接(查询显示在问题中)。当存在server = null的日志条目时,连接失败,因此不显示该记录。

我为修复此问题所做的是强制该排序列的LEFT JOIN:

    if (sortColumn.equals("hostName")) {
        sortColumn = "servers.hostName";
        criteria.createAlias("servers", "servers", JoinType.LEFT_OUTER_JOIN);
    }