How can I use CriteriaQuery with BETWEEN clause in Date? I have tried this without success;
the DAO method:
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;
}
and the Entity Class Registry:
@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 .....
}
With these error : "The method get(String) in the type Path is not applicable for the arguments (String, Date, Date)" ; How can I solve this?
Reviewing your code, it looks like a typo.
You have
// 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)));
Which is a compiler error, means that you're trying to call get(String)
in the type Path<Registry>
with the arguments (String, Date, Date)
Look at the javadoc of CriteriaBuilder.between(Expression,Value,Value), this is the method you need to call with 3 arguments not Path.get(String).
It should look something like this.
Path<Date> dateEntryPath = registry.get("dateEntry");
Predicate predicate = cb.between(dateEntryPath,init,currentDate);
c.select(registry).where(predicate);