问题
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:
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; } } }
Specify newly created dialect in Hibernate config file (hibernate.cfg.xml):
<property name="dialect">your.package.MySQL5Dialect</property>
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