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
  • 33,478
  • 73
  • 290
  • 513

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,136
  • 12
  • 51
  • 73
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
  • 99,167
  • 15
  • 158
  • 162