简体   繁体   中英

How to create an INSERT IGNORE query in Hibernate?

Hibernate has to make inserts in a table which has an unique field. I want to ignore duplicate entries so that my program keeps running. In MySQL I would simply say INSERT IGNORE , but I can't figure out how to do that in Hibernate. Any suggestions? Thanks!

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

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

if you are using a simple SQL query, use 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM