1

I am trying to make a @ManyToMany relationship between two entities.

Post Entity:

@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

}

And Label Entity:

@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.

}

When I try to save a Post, appears this error:

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]

And similar error when I try to save a Label:

org.h2.jdbc.JdbcSQLException: NULL not allowed for column "NOTICIA_ID"; SQL statement:
insert into label (id, color, name) values (null, ?, ?) [23502-194]

Point 1: I tried to save a Post without adding no Label (same error). I tried to save a Label without adding no Post (same error)

Point 2: I tried to save a Post adding Label (same error). I tried to save a Label adding Post (same error)

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Alberto Crespo
  • 2,429
  • 5
  • 28
  • 51

1 Answers1

1

Your mapping looks fine.

The problem could be in the way you are saving your entities.

Try the following code to persist your Post and its Label child entities.

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);

Also check out this answer for h2 specific problem.

Community
  • 1
  • 1
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78