如何从ConstraintViolationException获取数据库字段名称 - Hibernamte
问题描述:
如何让数据库领域引起ConstraintViolationException同时插入到数据库中休眠的名称。如何从ConstraintViolationException获取数据库字段名称 - Hibernamte
我的表像
mysql> desc Mytable;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | UNI | NULL | |
| city | varchar(20) | YES | UNI | NULL | |
+-------+-------------+------+-----+---------+----------------+
在矿井表记录
mysql> select * from Mytable;
+----+--------+-------+
| id | name | city |
+----+--------+-------+
| 1 | SATISH | BLORE |
+----+--------+-------+
1 row in set (0.00 sec)
现在,我尝试插入
"RAMESH","BLORE" through hibernate
。
它扔ConstraintViolationException due to "BLORE" (CITY) already Exist
。
如果我尝试插入。
"SATISH","MLORE" through hibernate
它扔ConstraintViolationException due to "SATISH" (NAME) already Exist
。
我的问题是 如何让字段名谁在通过Hibernate导致异常ConstraintViolationException。
答
由于可能有可能被侵犯时(例如组合键)方面的限制,你只有被违反了约束,而你的情况可能只是列名的名称(但是,我不完全对此肯定)。您可以拨来获得违反约束的名称。
谢谢托马斯,我试着用它给NULL getConstraintName()方法。 – sateesh 2012-02-06 13:59:36
@sateesh嗯,这可能是一个MySQL方言的问题。 AFAIK'MySQLDialect'不会覆盖'getViolatedConstraintNameExtracter()'方法,因此返回一个总是给出'null'作为约束名的提取器,然后传递给异常。在这种情况下,您似乎需要手动从嵌套的'SQLException'中获取约束名称。 – Thomas 2012-02-06 14:50:43