Hibernate: constraintName is null in MySQL

柔情痞子 提交于 2019-12-06 04:40:50

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()));
    }
    

Try use this:

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

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!!

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