Hibernate: constraintName is null in MySQL

时光怂恿深爱的人放手 提交于 2020-01-02 10:16:27

问题


I have a code using JPA with Hibernate 3.3.x. This Java code can be used with schemas stored either on Oracle 10g or MySQL 5.1.x. Tables are defined with constraints to define unique records. When a constraint violation occurs, I want to retrieve the constraint name from the exception.

With Oracle, the constraint name is properly retrieved. With MySQL, the constraint name is NULL.

Any idea how to get the constraint name with MySQL?

Thanks

Said


回答1:


I've come up with the following solution:

  1. Extend existing Hibernate MySQL5Dialect:

    public class MySQL5Dialect extends org.hibernate.dialect.MySQL5Dialect {
    
        /**
        * Pattern to extract violated constraint name from {@link SQLException}.
        */
        private static final Pattern PATTERN = Pattern.compile(".*constraint\\W+(\\w+).*", Pattern.CASE_INSENSITIVE);
    
        private ViolatedConstraintNameExtracter constraintNameExtracter;
    
        public MySQL5Dialect() {
            constraintNameExtracter = new ConstraintNameExtractor();
        }
    
        @Override
        public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() {
            return constraintNameExtracter;
        }
    
        private class ConstraintNameExtractor implements ViolatedConstraintNameExtracter {
    
            @Override
            public String extractConstraintName(SQLException sqle) {
                final String msg = sqle.getMessage();
                final Matcher matcher = PATTERN.matcher(msg);
                String constraintName = null;
                if (matcher.matches()) {
                    constraintName = matcher.group(1);
                }
    
                return constraintName;
            }
    
        }
    
    }
    
  2. Specify newly created dialect in Hibernate config file (hibernate.cfg.xml):

    <property name="dialect">your.package.MySQL5Dialect</property>
    
  3. Now getConstraintName() will return actual violated constraint name:

    try {
        ...
    } catch (ConstraintViolationException e) {
        LOG.error(String.format("Constraint=%s, code=%d", e.getConstraintName(), e.getErrorCode()));
    }
    



回答2:


Try use this:

try {
 // ...
} catch (ConstraintViolationException t) {
        if (t.getCause().getLocalizedMessage().contains("your_constraint_name")) {
            // ...
        } 
}



回答3:


Are you specifying the constraint names in MySQL at the database level? in Oracle the constraints get default names if not specified, however in MySQL I don't know, I think I heard once that if you don't specify a name for the constraint MySQL will not put a default one!!



来源:https://stackoverflow.com/questions/2118227/hibernate-constraintname-is-null-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!