So I have this username and password validation code using Java persistence.
public Subscriber validateLogin(String username, String password)
{
EntityManager em = getEntityManager();
Query q = em.createQuery("SELECT s FROM Subscriber s WHERE s.username = :username OR s.password = :password ");
q.setParameter("username", username);
q.setParameter("password", password);
try
{
return (Subscriber) q.getSingleResult();
}
catch (Exception e)
{
return null;
}
}
So I check if the subscriber return anything or null. Here is my code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
SubscriberJpaController sjc = new SubscriberJpaController();
Subscriber sub = sjc.validateLogin(jTextField1.getText(), jPasswordField1.getText());
System.out.println(sub);
}
and it returns null. Anything wrong with my code or logic?
there might be an exception thrown when you do the query. you have to print the stacktrace to see the cause.
I guess (not sure) the problem could be at the line
q.getSingleResult();if other configurations were correctly set.Jpa is expecting a unique result. however your query could generate a set of Subscribers by username=.. or password=…. e.g.
so the method getSingleResult() throws the exception.
also, you may consider to use jpa TypedQuery with generic instead of doing the class casting manually.