Reputation: 197
I am a JPA newbie and trying to understand @JoinTable annotation for Bidirectional OneToMany relationship b/w Project and Task Entities where Project can have multiple tasks.
I can use @JoinTable with Entity having @ManyToOne annotation, but when I am placing @JoinColumn on the other Entity having @OneToMany, I am not getting an option to specify "mappedBy" attribute on @ManyToOne annotation.
I would like to know why ?
I have tried placing @JoinTable annotation on both the entities but then Hibernate is itrying to insert two records in Join table
Project Entity :-
@Entity
@Data
public class Project {
@Id
@Column(name = "project_pk")
@GeneratedValue
private Long id;
@Column(name = "project_name")
private String name;
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL)
List<Task> tasks;
}
Tasks Entity :-
@Entity
@Data
public class Task {
@Id
@GeneratedValue
@Column(name = "task_pk")
private Long id;
public Task() {
}
private String name;
@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(name = "project_related_tasks",
inverseJoinColumns = @JoinColumn(name = "project_id", referencedColumnName = "project_pk"),
joinColumns = @JoinColumn(name = "task_id", referencedColumnName = "task_pk")
)
private Project project;
public Task(String name) {
this.name = name;
}
}
Upvotes: 0
Views: 2403
Reputation: 19956
There are two ways to implement one-to-many relations:
mappedBy
is used for the second way (using a foreign key). You don't have to specify mappedBy
, if you want to use a join table.
Using a join table is not very good idea because you can't control that join table using Hibernate. For example you can't just add a record to a join table directly.
what is @JoinColumn and how it is used in Hibernate
Upvotes: 1