JPA string comparison

I wrote a simple login system using a JPQL query that always does not return a 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 my own request:

 user = (Muser) em.createNativeQuery(qstring, Muser.class).getSingleResult(); 

or int expression:

 final String qstring="SELECT e FROM Muser e WHERE e.id = "+id; 

Everything goes well. What is the problem? Thanks a million!

+4
source share
2 answers

This might be a string comparison problem in your JPA provider. Are you checking it for case sensitive data?

You can also try (and this is the preferred option) using the options , instead of manually creating your statements. This is not only safe (prevents SQL injection), but also faster : not only for Java (you do not concatenate strings), but also for the database (a query can be prepared once for all executions). It could be something like this:

 final String qstring = "SELECT e FROM Muser e WHERE e.name = :name"; TypedQuery<Muser> query = em.createQuery(qstring, Muser.class); query.setParameter("name", name); user = query.getSingleResult(); 
+3
source

I think the problem is with string comparison. My solution to this problem:
using lowercase letters for comparison.

 final String qstring = "SELECT e FROM Muser e WHERE LOWER(e.name) = :name"; TypedQuery<Muser> query = em.createQuery(qstring, Muser.class); query.setParameter("name", name.toLowerCase()); user = query.getSingleResult(); 
+1
source

Source: https://habr.com/ru/post/1380334/


All Articles