【发布时间】:2017-10-17 14:54:07
【问题描述】:
我正在尝试在两个实体之间建立@ManyToMany 关系。
发布实体:
@Entity
@Table(name="Post")
public class Post {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "post_label", joinColumns = @JoinColumn(name = "POST_ID", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "LABEL_ID", referencedColumnName = "id"))
List<Label> labels = new ArrayList<Label>() ;
// getters and setters
}
和标签实体:
@Entity
@Table(name="Label")
public class Label{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id;
String name;
String color;
@ManyToMany(mappedBy = "labels")
List<Post> posts = new ArrayList<Post>() ;
// getters and setters.
}
当我尝试保存Post 时,出现此错误:
org.h2.jdbc.JdbcSQLException: NULL not allowed for column "LABEL_ID"; SQL statement:
insert into noticia (id, date, description, facebookid, postedonfacebook, postedonfake, publishdate, subtitle, title, type, visitorscount) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [23502-194]
当我尝试保存 Label 时出现类似错误:
org.h2.jdbc.JdbcSQLException: NULL not allowed for column "NOTICIA_ID"; SQL statement:
insert into label (id, color, name) values (null, ?, ?) [23502-194]
第 1 点:我尝试保存 Post 而不添加任何 Label(同样的错误)。
我试图保存 Label 而不添加任何 Post (同样的错误)
第 2 点:我尝试保存 Post 添加 Label(同样的错误)。
我试图保存Label 添加Post(同样的错误)
【问题讨论】:
-
假设您尝试使用
strategy=GenerationType.IDENTITY而不是strategy=GenerationType.AUTO -
它不起作用。
标签: java spring jpa many-to-many