How to create an INSERT IGNORE query in Hibernate?

Hibernate should do inserts in a table with a unique field. I want to ignore duplicate entries so that my program continues to work. In MySQL, I would just say INSERT IGNORE , but I cannot figure out how to do this in Hibernate. Any suggestions? Thanks!

+7
java hibernate
source share
2 answers

if you are using a simple SQL query, use the following code.

  Query query = session.createSQLQuery("INSERT IGNORE INTO user (name,username) VALUES (:name,:username)"); query.setParameter("name", name); query.setParameter("username", username); int i= query.executeUpdate(); 
+4
source share

Have you tried using the @SQLInsert annotation ? Thus, you can overwrite the Hibernate statement with your own SQL and use INSERT IGNORE :

 @SQLInsert(sql="INSERT IGNORE INTO CUSTOMER(id,name) VALUES(?,?)") class Customer{ ... } 
+6
source share

All Articles