Re: CriteriaQuery and JPA
Lele wrote:
I'm trying to make some examples of query using CriteriaQuery.
For now i'm [sic] trying to do something like that:
@Entity
@Table(name = "USERS")
public class ClassTest {
public ClassTrueAuth(){
this.username = "test";
}
@Id
@Column(name="testfield")
public boolean testField ;
@Column(name="username")
public String username;
}
and inside my code:
ClassTest cta = new ClassTest();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery cq = criteriaBuilder.createQuery(ClassTest.class);
Root<ClassTest> from = cq.from(ClassTest.class);
cq.select(from);
Predicate p = criteriaBuilder.equal(from.get(cta.username),"test");
Here's your problem -----------------------------^
cq.where(p);
TypedQuery<ClassTest> q = entityManager.createQuery(cq);
List<ClassTest> result = q.getResultList();
This give to me a NullPointerException... How to check if a string field=
is equal to a constant?
Read the Javadocs for 'Root#get(String attributeName)'. You gave a 'null' =
attribute name, and what you tried to do wasn't giving an attribute *name*,=
but an attribute *value*.
I tried to make another field in TestClass:
@Column(name="test")
public String test = "test";
and retry the same code above. The query string printed in console is:
The same code? The exact same code? Really? No change whatsoever? You d=
idn't substitute 'test' for 'username'? Are you sure? Because I don't bel=
ieve you. If it was the same code, it would have had the same result. You=
had a different result, ergo the code differed.
select classtest0_.testfield as testfield35_, classtest0_.username as
username35_, classtest0_.test as test36_ from USERS classtruea0_ where
classtruea0_.test=?
and 'result' is empty... Why where clause is test=? instead of
username=test ?
Because you gave it "test" as the attribute name.
'Root#get(String name)' takes the *name* of the attribute as an argument.
In your first attempt, you gave it a 'null' value, hence the NPE.
BTW, you said only that "[t]his give to me a NullPointerException" with no =
details such as, importantly, *where* the exception was and *what* it told =
you. Bug-hunting requires attention to detail, so don't omit the important=
details that tell you what exactly you did wrong.
In your second attempt, you told 'from()' to use "test" as the attribute na=
me, so it did.
Read the Javadocs.
<http://java.sun.com/javaee/6/docs/api/javax/persistence/criteria/Path.html=
#get(java.lang.String)>
--
Lew