开发者

Hibernate: constraintName is null in MySQL

I have a code using JPA with Hibernate 3.3.x. This Java code can be used with schemas stored either o开发者_开发知识库n 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜