1

如何在 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 .....
}

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

4

1 回答 1

4

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

你有

// 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)));

这是一个编译器错误,意味着您正在尝试使用参数调用get(String)类型Path<Registry>(String, Date, Date)

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

它应该看起来像这样。

 Path<Date> dateEntryPath = registry.get("dateEntry");
 Predicate predicate = cb.between(dateEntryPath,init,currentDate);
 c.select(registry).where(predicate);
于 2014-12-30T18:40:15.633 回答