pat3ck029 pat3ck029 - 2 months ago 8
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
.createEntityManagerFactory("test");
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!");
}else{
System.out.println("Login Success!");
UserAccounts login = (UserAccounts) query; //error here
System.out.println(login.getUserName());
}


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?
Thanks!

Answer

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

Comments