Java – how to check whether the user name exists in the database before submitting to create a user with Hibernate?
•
Java
Hi, I have a simple login service. I use GWT, hibernate & HSQLDB
Now I can create an account, but I need to add a function to check whether the user name is already in the database before submitting 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; } }
Solution
Query query= session.createQuery("from Account where name=?");
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 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码