简体   繁体   中英

catching ConstraintViolationException from jpa gives constraint name null value

I use jpa and hibernate to persist my data.My model is

@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;
}   

I am catching the ConstraintViolationException to catch if a user is violating a unique value. But when I try to access the constraintName using ConstraintViolationException.getConstraintName() gives me null value. How can I know which column violated the constraint so to warn the user?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM