【问题标题】:JPA 2.1 CriteriaQuery between Date日期之间的 JPA 2.1 CriteriaQuery
【发布时间】:2014-12-30 18:22:22
【问题描述】:

如何在 Date 中将 CriteriaQuery 与 BETWEEN 子句一起使用?我试过这个没有成功;

DAO 方法:

public List<Registry> listRegistry(Date init){
    List<Registry> registrys = null;
    try{
        Date currentDate = new Date();
        CriteriaBuilder cb = getEm().getCriteriaBuilder();
        CriteriaQuery<Registry> c = cb.createQuery(Registry.class);
        Root<Registry> registry= c.from(Registry.class);

        // get error here; "The method get(String) in the type Path<Registry> is not applicable for the arguments (String, Date, Date)"
        c.select(registry).where(cb.between(registry.get("dateEntry", init, currentDate)));

        registrys = getEm().createQuery(c).getResultList();

    }
    catch (NoResultException x) {
        //does nothing
    }
    return registrys;
}

和实体类注册表:

@Entity
public class Registry {

@GenericGenerator(name="gen",strategy="increment")
@GeneratedValue(generator="gen")
@Column(name = "id", unique = true, nullable = false, precision = 15, scale = 0)
@Id
private int id;

private Date dateEntry;

// getters and setters .....
}

出现这些错误:“Path 类型中的方法 get(String) 不适用于参数 (String, Date, Date)”;我该如何解决这个问题?

【问题讨论】:

  • 这是一个错字,请在此处查看您的代码registry.get("dateEntry", init, currentDate))。我觉得应该是cb.between(registry.get("dateEntry"), init, currentDate);
  • 对不起不明白你;我想我已经做到了你提到的这种方式

标签: jpa between criteriaquery


【解决方案1】:

查看您的代码,它看起来像是一个错字。

你有

// get error here; "The method get(String) in the type Path<Registry> is not applicable for the arguments (String, Date, Date)"
c.select(registry).where(cb.between(registry.get("dateEntry", init, currentDate)));

这是一个编译器错误,意味着您尝试使用 Path&lt;Registry&gt; 类型调用 get(String) 并使用参数 (String, Date, Date)

看javadoc CriteriaBuilder.between(Expression,Value,Value),这是您需要使用 3 个参数而不是 Path.get(String) 调用的方法。

它应该看起来像这样。

 Path<Date> dateEntryPath = registry.get("dateEntry");
 Predicate predicate = cb.between(dateEntryPath,init,currentDate);
 c.select(registry).where(predicate);

【讨论】:

  • 我会在几个小时内测试,如果解决了问题,我会告诉你;很高兴您的回答!
猜你喜欢
  • 2016-09-07
  • 2015-12-16
  • 1970-01-01
  • 2020-04-17
  • 2018-06-04
  • 2012-05-06
  • 2018-06-28
  • 1970-01-01
  • 2011-03-29
相关资源
最近更新 更多