我有一个从名为Card的类到名为Color的类的ManyToMany关系。我正在使用JPA和Hibernate。
Card.java
@Entity(name = "Cards")
public class Card
{
@Id
@Column(name = "card_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long cardId;
@ManyToMany(cascade = CascadeType.ALL)
private List<Color> colors;
}
Color.java
@Entity(name = "Colors")
public class Color
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long colorId;
@Column(unique = true)
private String name;
}
但是如果我坚持使用Card,则会抛出异常,因为Black已经包含在Colors中。
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Black' for key 'UK_sd7tby3rtx8snv2vlbmlmy69o'
但是我希望Colors.name是唯一的,如果颜色已经保留并且使用持久颜色,JPA应该搜索颜色。
答案 0 :(得分:0)
所以,我认为您需要OneToMany
关系,并向Color
类添加新文件,如下所示:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "card")
private List<Color> colors;
//Add to `Color`class
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "card_id", nullable = false)
private Card card;