0

i'm learning Java hibernate, found an example of "insert ignore",

Query query = getSession().createSQLQuery("INSERT IGNORE INTO TABLA (ID, VAR) VALUES (:id, :var)");
UUID id = UUID.randomUUID();
query.setParameter("id", id);
String var = "abcde";
query.setParameter("var", var);
query.executeUpdate();

This will "insert ignore" 1 entry. I may have 100+ var as input, but only 1 or 2 will not be in the existing table, i don't know which ones.

If i set Parameters of 100 of values with a loop, it may work. But is there a better may ? given i may just need to insert 1 or 2 of them really.

Or i should ask this: given a list of 100 var string, find out the a few not in existing table, without using loop.

user3552178
  • 2,719
  • 8
  • 40
  • 67

1 Answers1

0

You could use the MySQL ON DUPLICATE KEY UPDATE feature.

For example:

INSERT INTO TABLA (ID, VAR) VALUES (1, 1), (2, 2), ... ON DUPLICATE KEY UPDATE ID=ID;

I'm not familiar with java or hibernate, hence my answer being a raw query. If you need help figuring out the exact syntax, this question might be a good resource for it.

Also, generally speaking, ON DUPLICATE KEY UPDATE is much safer than INSERT IGNORE because the latter will ignore all errors, while the former will only ignore duplicate inserts.

Hope this helps!

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80