列不允许使用ManyToMany RelationShip NULL

时间:2017-05-18 00:34:24

标签: java spring jpa many-to-many

我想在两个实体之间建立@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(同一错误)

1 个答案:

答案 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个答案。

相关问题