H2 Java Insert Ignore - Allow Exception

I am working on a java plugin interface with an H2 database. What I really want is the "Insert Ignore" operator; however, I know that H2 does not support this. I also know about merging, but this is really not what I want, if the record exists, I do not want to change it.

What I am considering is just to start the insert and allow the duplicate key exception. However, I do not want this to populate my log file. The DB call happens in the imported class, which I cannot change. So my questions are:

  • Is this a reasonable thing? I'm not one of those who make mistakes, but in this case it seems to be the best way (this should not happen so much).
  • How can I avoid throwing this exception from my log file? If there is no way to block exceptions on the stack, can I redirect the output of the stack trace that will be displayed?

Thanks.

+4
source share
1 answer

One solution is to use:

insert into test select 1, 'Hello' from dual where not exists(select * from test where id = 1) 

This should work for all databases (with the exception of the double part, you may need to create your own dummy table with one row).

To disable registration exceptions, add ;trace_level_file=0 to the database URL:

 jdbc:h2:~/test;trace_level_file=0 

or run the SQL statement:

 set trace_level_file 0 
+9
source

All Articles