从jpa捕获ConstraintViolationException会给出约束名称null值

时间:2015-06-23 11:31:40

标签: java mysql hibernate jpa

我使用jpa和hibernate来保存我的数据。我的模型是

@Entity
@Table(name = "user", uniqueConstraints=@UniqueConstraint(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访问constraintName时,getConstraintName()给出了null值。如何知道哪个列违反了约束以便警告用户?

1 个答案:

答案 0 :(得分:0)

尝试:cve.getCause().getMessage()