2015-06-23 29 views
0

我使用JPA和休眠堅持我的data.My模型從JPA醒目ConstraintViolationException給出約束名空值

@Entity 
@Table(name = "user", [email protected](columnNames={"username"}, name="username")) 
public class User implements Serializable { 
    @Transient 
    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 

    @Column(name = "username", nullable = false) 
    private String username; 

    @Column(name = "password", nullable = false) 
    private String password; 

    @Column(name = "user_role", nullable = false) 
    private UserRole userRole; 
} 

我捕捉ConstraintViolationException趕上如果用戶違反獨特的價值。但是,當我嘗試訪問約束使用ConstraintViolationException.getConstraintName()給我空值。我如何知道哪個列違反了約束條件,以警告用戶?

回答

0

嘗試:cve.getCause().getMessage()

+0

它讓重複的條目 '管理員' 關鍵 '用戶名'。所以我需要提取價值和關鍵。這來自'MySQLIntegrityConstraintViolationException'。我能確定這將永遠如此嗎?沒有更通用的方法嗎?如果違反了一個以上的約束條件會怎樣?必須有更通用的(自動)方式。 – Apostolos

+0

我發現了類似的問題:http://stackoverflow.com/questions/2118227/hibernate-constraintname-is-null-in-mysql/14498717#14498717 – user3207081