在提交使用Hibernate创建用户之前,如何在数据库中检查用户名?

xyb*_*rek 3 java gwt hibernate

您好,我使用GWT,Hibernate和HSQLDB进行了简单的登录服务.

现在我可以创建帐户,但是,我需要添加一个功能,在提交到数据库之前检查用户名是否已经在数据库中.

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

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;
      }
}
Run Code Online (Sandbox Code Playgroud)

Adi*_*Adi 5

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
} 
Run Code Online (Sandbox Code Playgroud)