Is there any big advantage on this approach:
@Entity
public class A {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "ID_B")
private B b;
}
@Entity
public class B {
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
private List<A> aList;
}
...instead of this?...
@Entity
public class A {
@Column(name = "ID_B")
private Long idB;
}
@Entity
public class B {
//no reference to A
}
I thing the second one is better for encapsulation (as I have A and B classes in different projects, and the second don't need to reference the fist).
One advantage is that using proper JPA relationships allow you to fetch A from the database, and use a simple getter on A to get B: myA.getB()
Whereas if you use a long, you will need to always manually query the database again when you want to fetch some B.
Note that you are not obligated to declare the relationship both ways. Something like this is perfectly valid:
@Entity
public class A {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "ID_B")
private B b;
}
@Entity
public class B {
//no reference to A
}
Of course, it all depends on what you are trying to achieve!