【问题标题】:ManyToMany RelationShip NULL not allowed for columnManyToMany RelationShip NULL 不允许用于列
【发布时间】: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


【解决方案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);

还可以查看thish2 特定问题的回答。

【讨论】:

  • 是否可以在不添加labels 的情况下保存post
猜你喜欢
  • 2020-12-18
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2013-08-24
  • 2014-04-19
相关资源
最近更新 更多