I’ve written a simple login system using a JPQL query, which always returns no result:
public boolean check(String name, String password) {
final String qstring="SELECT e FROM Muser e WHERE e.name = '"+name+"'";
Muser user;
try{
user = em.createQuery(qstring, Muser.class).getSingleResult();
}
catch(NoResultException e){
return false;
}
return password.equals(user.getPassword());
}
When I changed it to a native query:
user = (Muser) em.createNativeQuery(qstring, Muser.class).getSingleResult();
or an int expression:
final String qstring="SELECT e FROM Muser e WHERE e.id = "+id;
It goes all right. What’s the problem? Thanks a million!
It might be a problem with string comparison in your JPA provider. Do you test it on the case-sensitive data?
You could also try (and it’s the preferred way) using parameters instead of crafting your statement by hand. It’s not only safer (prevents SQL injection) but also faster: not only for Java (you don’t concatenate Strings) but also for the DB (the query can be prepared once for all executions). It might be something like this: