如何从ConstraintViolationException获取数据库字段名称 - Hibernamte [英] How to Get DB Field name from ConstraintViolationException - Hibernamte

查看:1171
本文介绍了如何从ConstraintViolationException获取数据库字段名称 - Hibernamte的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有Table Like


如何获取DB字段的名称导致ConstraintViolationException,同时在hibernate中插入数据库。

  mysql> desc Mytable; 
+ ------- + ------------- + ------ + ----- + --------- + ---------------- +
|字段|类型|空| Key |默认|额外|
+ ------- + ------------- + ------ + ----- + --------- + ---------------- +
| id | bigint(11)| NO | PRI | NULL | auto_increment |
|名称| varchar(20)|是| UNI | NULL | |
|城市| varchar(20)|是| UNI | NULL | |
+ ------- + ------------- + ------ + ----- + --------- + ---------------- +

记录在表中是

  mysql>从Mytable中选择*; 
+ ---- + -------- + ------- +
| id |名称|城市|
+ ---- + -------- + ------- +
| 1 | SATISH | BLORE |
+ ---- + -------- + ------- +
1行(0.00秒)


现在,我试图插入

RAMESH,通过hibernate



抛出由于BLORE(CITY)已存在

if im插入。

  SATISH,MLORE通过hibernate 

抛出 ConstraintViolationException由于SATISH(NAME)已存在



我的问题是
如何获得fieldName通过Hibernate导致异常ConstraintViolationException 。

解决方案

由于可能存在其他可能违反的约束条件(例如组合键),因此只能使用约束名称这是违反,你的情况可能只是列的名称(但是,我不完全确定)。您可以通过在 ConstraintViolationException 中调用 getConstraintName()来获取违反约束的名称。 $ b

How to get the Name of the DB field causing ConstraintViolationException while inserting in to Database in hibernate.

I have the Table Like

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

And records inthe table are

mysql> select * from Mytable;
+----+--------+-------+
| id | name   | city  |
+----+--------+-------+
|  1 | SATISH | BLORE |
+----+--------+-------+
1 row in set (0.00 sec)

Now, im trying to insert

"RAMESH","BLORE" through hibernate.

It is throwing ConstraintViolationException due to "BLORE" (CITY) already Exist.

if im trying to insert.

"SATISH","MLORE" through hibernate

It is throwing ConstraintViolationException due to "SATISH" (NAME) already Exist.

My question is how to get fieldName who is causing the exception ConstraintViolationException through Hibernate.

解决方案

Since there might be other constraints that could be violated (e.g. combined keys), you only have the name of the constraint that is violated, which in your case might just be the column name (however, I'm not entirely sure about that). You can get the name of the violated constraint by calling getConstraintName() on the ConstraintViolationException.

这篇关于如何从ConstraintViolationException获取数据库字段名称 - Hibernamte的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆