2011-04-14 44 views
1
mysql> alter table metakey add constraint Name unique(name); 
mysql> desc metakey; 
+-------+---------------------+------+-----+---------+----------------+ 
| Field | Type    | Null | Key | Default | Extra   | 
+-------+---------------------+------+-----+---------+----------------+ 
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment | 
| name | varchar(45)   | NO | UNI |   |    | 
+-------+---------------------+------+-----+---------+----------------+ 


@Entity 
@Table(name = "metakey",uniqueConstraints={@UniqueConstraint(name="Name",columnNames={"name"})}) 
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE) 
public class MetaKey implements Serializable{ 
    @Id @Column @GeneratedValue private Long id; 
    @Column private String name; 
} 


sess.save(obj); 
.. 
}catch(ConstraintViolationException cve){ 
    log.error(cve.getMessage()); 
    log.info("Constraint name:"+cve.getConstraintName()); 
} 

我在日誌中得到這些 - cve.getConstraintName()返回null休眠ConstraintViolationException getConstraintName

org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 
org.hibernate.util.JDBCExceptionReporter - Duplicate entry 'Unit' for key 'Name' 

could not insert: [com.comp.MetaKey] 
Constraint name:null 

有沒有辦法找到約束的名字嗎?

Server版本:56年5月1日 Hibernate的版本:3.6

+0

使用PostgreSQL的同樣的問題 – dmonti 2016-11-24 13:11:44

回答

1

的Javadoc說:

返回違反 約束的名稱,如果知道的話。

Returns: 
    The name of the violated constraint, or null if not known. 

所以我想MySQL驅動程序不給訪問違反約束名稱在它產生的的SQLException,或者Hibernate不知道如何從SQLException中得到它。

使用調試器查看SQLException的詳細信息,並查看它是否可以從某處提取。如果可以,則嘗試擴展方言以提取約束名稱。

+1

cve.getCause().getMessage()返回「Name'重複條目'Unit',其中'Name'是約束名稱 – yodhevauhe 2011-05-28 07:55:02