Reputation: 35326
I made the username
as PRIMARY KEY in the database. Creating new account with the same username that is already in the database cause this error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'someuser' for key 'PRIMARY'
What is the best way to work around this problem?
I tried this approach:
Query query = session.createQuery("from Account where name= :name");
query.setParameter("name", user.getUsername());
List<Account> result = query.list();
if (!result.isEmpty()) {
log.debug("User already exist");
}
However log is not triggered even if record exist in database.
Upvotes: 0
Views: 1512
Reputation: 6158
Try this one
String hql = "from Account where name=?";
List <Account> recordList= session.createQuery(hql).setString(0,"xybrek").list();
if(recordList!=null && recordList.size>0)
{
log.debug("User already exist");
}
Upvotes: 1
Reputation: 100195
Well, wont using INSERT IGNORE aid in solving this kind of problem..? "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
Upvotes: 0