pat3ck029 pat3ck029 - 1 year ago 67
Java Question

Login using hibernate/JPA

Hi i'm trying to create a login form and use hibernate framework.

String user = request.getParameter("username");
String password = request.getParameter("password");

EntityManagerFactory entityFactory = Persistence
EntityManager entityManager = entityFactory.createEntityManager();

String select = "SELECT userName, passWord FROM UserAccounts WHERE userName='"
+ user + "' and passWord='" + password + "'";

Query query = entityManager.createQuery(select);

if(query.getResultList().size() == 0){
System.out.println("Account does not exist!");
System.out.println("Login Success!");
UserAccounts login = (UserAccounts) query; //error here

The problem is i'm getting an error when trying to cast the query result to the accounts object.

What is the correct way of converting?

Answer Source

Use variables and bind the parameters to prevent injection attacks and select the UserAccounts object.

String select = "SELECT ua FROM UserAccounts ua WHERE ua.userName=:userName and ua.passWord=:password";

Query query = entityManager.createQuery(select);
query.setParameter("userName", user);
query.setParameter("password", password);

Use getSingleResult(), because a user/password should only identify one user. (Also prevents some attacks) and cast it to the class you selected (a UserAccounts)

UserAccounts ua = (UserAccounts) query.getSingleResult();

PS: Never store passwords in plain-text in the database. Use a one-way hash instead. E.g. bcrypt

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download