I am curious as to why it is possible, with the CriteriaBuilder
class of JPA 2, to create such queries. Suppose I have a User
class with a persisted String
called name
as attribute. Why can I write this?
CriteriaBuilder builder = mgr.getCriteriaBuilder();
CriteriaQuery<User> crit = builder.createQuery(User.class);
Root<User> user = crit.from(User.class); // 1
crit.select(user)
.where(builder.equal(user.get(User_.name), 2.5)); // 2
First, at Marker 1: Why must I indicate User.class
again? Isn't my CriteriaQuery supposed to know I'm interested in users anyway? Doesn't it break type safety to possibly inject another class here?
Second, at Marker 2: The name
property is a String
. Why can I compile nonsense like this, comparing a String
with a double? In other words, why is the signature of the called equal
method this:
public Predicate equal(Expression<?> x, Object y)
instead of a presumably more type safe version as follows?
public <T> Predicate equal(Expression<T> x, T y)
Would other query frameworks like Querydsl provide a better solution to this issue?