So I have 2 entities - Post and Tag and there is a many to many relation between them. I also have a CSV file and need to pre-populate the database (it contains post details including the ids of the matching Tag entities). Moreover following DDD, the Post entity is the Aggregate root with its PostRepository. Given below are the java classes: -
Code:
@Entity
public class Post{
@Id
@GeneratedValue
private long id;
@ManyToMany(cascadeType = {MERGE, PERSIST})
@JoinTable(name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private Set<Tag> tags = new HashSet<>();
// getters ommited.
public void addTag(Tag tag){
tags.add(tag);
tag.getPosts().add(this);
}
}
@Entity
public class Tag{
@Id
private long id;
private Set<Post> posts = new HashSet<>();
// getters ommited.
}
}
Repository interface below : -
public interface PostRepo extends Repository<Post, Long>{
void save(Post p);
}
Database pre-loading code below : -
Code:
@Service
public class Service {
@Inject
private PostRepo repo;
@PostConstruct
void init(){
// parse CSV file and get a Stream<String[]> stream
stream.foreach( splits -> {
long tagId = Long.parseLong(splits[0]);
Post post = new Post();
post.add(new Tag(tagId);
repo.save(post);
}
}
}
While prepopulating the DB using the
Code:
PostRepo::save(post)
method I am running into a Primary key constraint validation error, and I think the reason behind that being while adding a Post entity I am also trying to add a new Tag with the same id as a pre-existing Tag entity.
So here is my question how can I do it correctly without adding a TagRepository and using the saveOrUpdate method of the TagRepository please?