Trying to create a many-to-many relationship using Java Persistence annotations for the first time.
Scenario:
Java class Project
contains subprojects, which is just a List
of Projects
. There is no inverse (no superproject) member. So I thought the many-to-many relationship would be perfect for this
@ManyToMany(fetch = FetchType.EAGER, targetEntity = ProjectEntity.class, mappedBy = "project")
@Override
public List<ProjectImpl> getSubProjects() {
return super.getSubProjects();
}
Q1: Is this the correct way to persist a project with a list of subprojects?
Q2: Also, i am currently getting the error: mappedby reference an unknown target property
. I found this highly rated thread for the error: mappedBy reference an unknown target entity property however i don't have a one one-to-many / many-to-one inverse or two different classes here
Edit: Based on Feedback, i changed the relation to one-to-many and added a JoinTable annotation based on the example in https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-association-collections . However i get the error A Foreign key refering de.otsd.worklog.database.ProjectEntity from de.otsd.worklog.database.ProjectEntity has the wrong number of column. should be 2
)
@OneToMany(fetch = FetchType.EAGER, targetEntity = ProjectEntity.class)
@JoinTable(
name = "ProjectToSubproject",
joinColumns = @JoinColumn(name = "project_id"),
inverseJoinColumns = @JoinColumn(name = "subproject_id")
)
@Override
public List<ProjectImpl> getSubProjects() {
return super.getSubProjects();
}
@EmbeddedId
@Override
public ProjectKey getProjectKey() {
return new ProjectKeyEntity(super.getProjectKey());
}