我有2个表:
表1:用户
userid
titleid (Links to title table below)
name
surname
表2:标题
titleid
title
用户实体类:
@Entity
@Table(name="user",
uniqueConstraints={@UniqueConstraint(name="user_unique", columnNames={"titleid", "name"})})
@NamedQuery(name="User.findAll", query="SELECT e FROM user e")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="userid", insertable=false, updatable=false, unique=true, nullable=false)
private long userId;
//bi-directional many-to-one association to Title
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="titleid")
private Title title;
@Column(name="name", nullable=false, length=45)
@NotEmpty(message="Please enter name.")
private String name;
在表1中,我希望titleid和name组合是唯一的。我已经在数据库和实体上添加了约束:
uniqueConstraints={@UniqueConstraint(name="user_unique", columnNames={"titleid", "name"})})
现在,当我尝试插入或更新记录与另一条记录完全相同时,我得到以下异常,这是100%正确的。
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry for key 'user_unique'
我的问题是如何在Spring Boot中处理它?我正在使用最新版本的Spring Boot,Hibernate等。是否有一个注释我可以放在表1中的name列中,它会优雅地处理它并返回一条好消息,或者我必须在异常中处理这个问题吗?或者这样做完全错了?
谢谢