我想在两个实体之间建立@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
(同一错误)
答案 0 :(得分:1)
您的映射看起来很好。
问题可能在于您保存实体的方式。
尝试使用以下代码来保留Post
及其Label
子实体。
Post post = new Post();
List<Label> labels = new ArrayList<>();
Label firstLabel = new Label();
firstLabel.setColor("MAROON");
firstLabel.setName("MAROONIFIED");
labels.add(firstLabel);
Label secondLabel = new Label();
secondLabel.setColor("BLUE");
secondLabel.setName("BLUEFIED");
labels.add(secondLabel);
post.setLabels(labels);
postRepository.save(post);
另请查看h2
特定问题的this个答案。