0

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.

quarks
  • 31,298
  • 67
  • 266
  • 478

2 Answers2

1

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

  }
subodh
  • 6,004
  • 12
  • 48
  • 69
0

Well, wont using INSERT IGNORE aid in solving this kind of problem..? "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Community
  • 1
  • 1
Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158