【问题标题】:Max of two Date columns in Hibernate CriteriaHibernate Criteria 中最多两个日期列
【发布时间】:2015-04-27 06:51:05
【问题描述】:

我有两个日期列,一个是 createDate,另一个是 modifiedDate。 现在我想得到这两个日期列的最大值。

ProjectionList projectionList = Projections.projectionList();
projectionList.add( Projections.max("createdDate"));

如何在 Projection 中添加另一个日期。并找到两者的最大日期。 找不到任何具体的方法来做到这一点。

实体是:-

package com.xyz.DemoEntity;


import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Formula;


@Entity
public class DemoEntity {

    private Integer id;
    private Date createdOn;
    private Date modifiedOn;

    @Formula("CASE WHEN createdOn > modifiedOn THEN createdOn ELSE modifiedOn  END")
    private Date maxDate;

    /**
     * @return the id
     */
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(updatable=false)
    @Temporal(TemporalType.DATE)
    public Date getCreatedOn() {
        return createdOn;
    }
    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    @Temporal(TemporalType.DATE)
    public Date getModifiedOn() {
        return modifiedOn;
    }

    public void setModifiedOn(Date modifiedOn) {
        this.modifiedOn = modifiedOn;
    }

}

【问题讨论】:

  • 你能给出你想要做什么的 sql 查询吗?
  • 我使用的是hibernate 4和ms sql server。
  • 您是否尝试在projectionList 中添加另一个投影,例如projectionList.add( Projections.max("modifiedDate"));
  • 但我认为它会给出两种不同的结果。一个是 createdDate 的最大值,第二个是 modifiedDate 的最大值。但我需要两者的综合结果。
  • 嗯。 createDate > modifiedDate 真的有可能吗?

标签: java hibernate hibernate-criteria


【解决方案1】:

你应该引入一个用@Formula注释的人工列

这样

@Formula("CASE WHEN createDate > modifiedDate THEN createDate ELSE modifiedDate  END")
private Date maxDate;

然后使用projectionList.add( Projections.max("maxDate")); 得到最大值。

【讨论】:

  • 这个字段是否会持久化到数据库中?
  • 没有。它只是 SELECT 块中的一种计算字段
  • 得到这个异常:org.hibernate.QueryException: could not resolve property: maxDate of: com.xyz.DemoEntity
  • 编辑问题以包含 com.xyz.DemoEntity
  • 你没有 maxDate 的 getter/setter
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 2017-08-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多