Hibernate unique Configuration
Yesterday, I created a table, mapped it through hibernate, and added the unique restriction. when I ran the JUnit test, I found that hibernate did not perform a uniqueness check on the configured fields, but passed the test directly, save to database. It is puzzling!
Later, I checked the hibernate document and checked it online and found that unique was valid only when the table was created by hibernate itself, that is
- Verify the structure of the created database table when loading hibernate in validate.
- Create loads hibernate each time and re-creates the database table structure
- Create-drop is created when Hibernate is loaded. Exit is to delete the table structure
- Update load hibernate automatically updates the database structure
Hibernate. hbm2ddl. Auto = Update, create or create-drop. If no table exists in the database, the unique constraint is added to the configured field when hibernate creates the table.
Hibernate. hbm2ddl. if there are tables in the database during auto = Update, Hibernate does not check whether the configured fields have unique constraints. If other configurations are the same, no update is performed. Therefore, the table has no unique constraints.
In short: If you want to use the unique constraint, the table must be generated by hibernate or added to the table by yourself. Therefore, the uniqueness constraint on the field is checked on the database.
Hibernate exception capture
When doing the test, insert duplicate data in the table that added the uniqueness constraint, the database reported "ORA-00001: violation of unique constraints (Oracle username. oracle constraint name) ", originally intended to get exception information at the action layer, exceptions cannot be caught through jdbcexception and hibernateexception, and exceptions can be caught through runtimeexception and exception, however, the caught exceptions pass through E. getlocalizedmessage () is called and only "cocould not execute JDBC batch update; Nested" is displayed.
Exception is org. hibernate. Exception. constraintviolationexception: cocould not execute JDBC batch Update ", but there is no underlying database exception. You can also query the document to find that if you want to obtain the underlying exception, you must use E. getcause () is obtained recursively until E. getcause () = NULL to obtain the underlying exception.
For example:
catch (RuntimeException e) {new DaoTest() {private void showTraces(Throwable t) {Throwable next = t.getCause();if (next == null) {System.out.println(t.getMessage());} else {showTraces(next);}}}.showTraces(e);}