I am using Spring Data JPA (with hibernate as the provider) for my project and wondering when do I need a bidirectional mapping between entities?
In my use case, I have a CategoryGroup
entity having a @ManyToOne
relationship to a Department
entity. Currently, I don't have a corresponding @OneToMany
relation in the Department
entity. From what I could understand looking at other posts unless I need to delete via my entity/hibernate, I probably don't need to do it. I am wondering what else do I get by having a bidirectional relationship?
This is my Department
excluding the accessors:
@Entity
@Table(name="dbo.Department")
public class Department
{
@Id
@Column(name="id")
private long id;
@Column(name="name")
private String name;
}
This is CategoryGroup
excluding accessors:
@Entity
@Table(name="dbo.CategoryGroup")
public class CategoryGroup
{
@Id
@Column(name="id")
private long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="dept_id")
private Department department;
@Column(name="name")
private String name;
public CategoryGroup()
{
}
public CategoryGroup(String name, Department department)
{
this.name = name;
this.department = department;
}
}
As a follow up, my structure is hierarchical in nature. Category
entity has a @ManyToOne
relationship to a CategoryGroup
entity and further on SubCategory
entity has a @ManyToOne
relationship to a Category
entity.
If I keep adding bidirectional relation mapping on the parent side of the relationship then would that mean that once I retrieve the Department
I will end up getting the whole entity hierarchy right upto SubCategory
? For my use case that won't be desirable. Will marking the relationship with FetchType.LAZY
alleviate that?
Thanks