2017-05-18 10 views
1

2つのエンティティ間に@ManyToManyの関係を作成しようとしています。ManyToMany RelationShipカラムにNULLを使用できません

ポストエンティティ:

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

および類似エラー

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

ポイント1:私はLabelを保存しようとすると、私は何のLabel(同じエラー)を添加しないなしPostを保存しようとしました。 私はPost(同じエラー)

ポイント2を添加しないことなくLabelを保存しようとした:私はPost追加Label(同じエラー)を保存しようとしました。 Labelを保存しようとしましたPost(同じエラー)

+0

'strategy = GenerationType.AUTO' –

+0

の代わりに' strategy = GenerationType.IDENTITY'を使用しようとしたとします。 –

答えて

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答えをチェックしてください。

+0

'labels'を追加せずに' post'を保存することはできますか? –

+0

あなたの答えを試すのと同じエラー。 –

関連する問題