Facing problem inserting records in intermediate table. Post and Tag tables are sharing many to many relationship using intermediate table post_tag;
Post table: id (pk), post, created_by, created_on, modified_by, modified_on
Tag table: id (pk), tag, created_by, created_on, modified_by, modified_on
Post_Tag table: post_id, tag_id (pk post_id and tag_id), created_by, created_on, modified_by, modified_on
Entities:
// ID class
@Embeddable @Data @NoArgsConstructor @AllArgsConstructor
public class PostTagId
implements Serializable {
@Column(name = "post_id")
private Long postId;
@Column(name = "tag_id")
private Long tagId;
}
@Entity
@Table(name = "post_tag")
@EntityListeners(AuditingEntityListener.class)
@Data
@EqualsAndHashCode(callSuper = false)
public class PostTag extends Auditable<String> {
@EmbeddedId
private PostTagId id;
@ManyToOne
@MapsId("postId")
@JoinColumn(name="post_id")
private Post post;
@ManyToOne
@MapsId("tagId")
@JoinColumn(name="tag_id")
private Tag tag;
public PostTag(Post post, Tag tag) {
this.post = post;
this.tag = tag;
this.id = new PostTagId(post.getId(), tag.getId());
}
}
Using springboot(AuditingEntityListener) to add audit columns. Post and Tag entities are somewhat like -
///////////Tag
@Data
@EqualsAndHashCode(callSuper = false, exclude = {"postTags"})
@ToString( exclude = {"postTags"})
@Entity
@Table(name = "tag")
@EntityListeners(AuditingEntityListener.class)
public class Tag extends Auditable<String> {
@Id
private Long id;
@Column(name = "tag")
private String tag;
@OneToMany(mappedBy = "tag", cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private Set<PostTag> postTags;
}
//////////////POST
@Data
@EqualsAndHashCode(callSuper = false, exclude = {"postTags"})
@ToString( exclude = {"postTags"})
@Entity
@Table(name = "post")
@EntityListeners(AuditingEntityListener.class)
public class Post extends Auditable<String> {
@Id
private Long id;
@Column(name = "post")
private String post;
@OneToMany(mappedBy = "post", cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private Set<PostTag> postTags;
public void addTag(Tag tag) {
PostTag postTag = new PostTag(this, tag);
if (postTags == null) {
postTags = new HashSet<>();
}
postTags.add(postTag);
tag.getPostTags().add(postTag);
}
}
Code snippet for insertion of tags using addTag() method -
public Post create(Post post) {
// DefaultTag is some default tag getting from repository
post.addTag(DefaultTag)
return postRepo.save(post);
}
Insert in post_tag is trying to insert null post_id.
Hibernate:
insert
into
post_tag
(created_by, created_on, modified_by, modified_on, post_id, tag_id)
values
(?, ?, ?, ?, ?, ?) [0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper SQL Error: 0, SQLState:
23502 [0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper ERROR: null
value in column "post_id" violates not-null constraint Detail:
Failing row contains (null, 100, anonymousUser, anonymousUser,
2020-07-06 15:22:19.227-06, 2020-07-06 15:22:19.227-06).