How to check user name if exist in database before committing to create user with Hibernate?
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;
开发者_如何学JAVA }
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;
}
}
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
}
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");
}
}
write the logic of checking already available user in set method and it should return an exception when user already exists. however i am very new to hibernate lets see whether any expert have a simple solution.
精彩评论