org.springframework.dao.DataIntegrityViolationException misreporting cause?

后端 未结 2 604
眼角桃花
眼角桃花 2021-02-07 13:38

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\

相关标签:
2条回答
  • 2021-02-07 14:22

    you can get the Constain name directly from Hibernate's exception type. use

    getConstraintName

    property to get DB constrain name.

    } catch (ConstraintViolationException conEx) {
                if (conEx.getConstraintName().contains("PROJECT_UK")) {
                    //TODO Project Entity is violating it's constrain
    

    I've used contains because I want this app to run on multiple DB Schemas. By default getConstraintName comes with DB name like

    MyDBName.ConstrainName

    0 讨论(0)
  • 2021-02-07 14:27

    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.

    0 讨论(0)
提交回复
热议问题