JPA 2.1 日期之间的标准查询



如何在Date中使用带有BETWEEN 子句的 CriteriaQuery?我试过这个没有成功;

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 .....
}

出现这些错误:"路径类型中的方法get(字符串)不适用于参数(字符串,日期,日期)";我该如何解决这个问题?

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

你有

// 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<Registry>中的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);

相关内容

  • 没有找到相关文章

最新更新