How to check user name if exist in database before committing to create user with Hibernate?
10,809
Solution 1
Query query= session.createQuery("from Account where name=?");
Account user=(Account)query.setString(0,user.getName()).uniqueResult();
if(user!=null){
//Do whatever you want to do
}else{
//Insert user
}
Solution 2
I'd add something like this to your Account
class. This ensures that the check is always performed when the model is saved, instead of having to manually add the check to every piece of code that saves the model.
@PrePersist
public void prepareToInsert() {
List<User> conflicts = find("user=?").fetch();
if (!conflicts.isEmpty()) {
throw new IllegalArgumentException("username `" + name + "` is already taken");
}
}
Author by
quarks
Updated on June 30, 2022Comments
-
quarks almost 2 years
Hi there is a simple login service I made with GWT, Hibernate & HSQLDB.
Right now I can create accounts, however, I need to add a functionality that will check if the username is already in the database before committing to the database.
LoginServiceImpl.java
@Override public void createAccount(Account user) { try { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); }catch (HibernateException e) { e.printStackTrace(); }catch (InvocationException e) { e.printStackTrace(); } }
Account.java
public class Account implements Serializable { Long id; String name; String password; public Account() { } public Account(Long id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setId(Long id) { this.id = id; } }