Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.springframework.dao.DataIntegrityViolationException misreporting cause?

I'm using hibernate to insert to a mysql table on which all columns are defined as not null. It has a unique primary key and another unique index on several columns.

I'm getting the following error:

org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into MY_TABLE(col1, col2, col3, col4, ID_) values (?, ?, ?, ?, ?)]; constraint [null]

This error is in customer logs and I can't reproduce the problem myself, so I can't put in debugging to see what the values are in the insert statement.

My understanding is that "constraint [null]" means a "not null" constraint is being violated. However, looking at my code, I cannot see any possible way that any of the data could be null at the time of the insert, unless hibernate is trying to insert a null ID (which would be a very bad bug in hibernate and so seems unlikely).

However, I can see how it could happen that a unique constraint is being violated. Is it possible that the message is misleading and I'm actually getting a unique key violation? Does "constraint[null]" always mean a not null constraint was violated?

like image 850
Dana Avatar asked Nov 05 '12 19:11

Dana


1 Answers

If you search for the callers of the constructor of DataIntegrityViolationException in the Spring source code, you'll find that it's called in org.springframework.orm.hibernate3.SessionFactoryUtils:

return new DataIntegrityViolationException(ex.getMessage()  + "; SQL [" + jdbcEx.getSQL() +
                "]; constraint [" + jdbcEx.getConstraintName() + "]", ex);

So the exception is caused by a violated constraint, and null is the name of the constraint as returned by the JDBC exception. So you should blame the MySQL driver for not populating the violated constraint name in the JDBC exception. But the violated constraint could be any constraint, and not necessarily a not null constraint.

like image 136
JB Nizet Avatar answered Oct 13 '22 19:10

JB Nizet