Java JPA @OneToMany need to reciprocate @ManyToOne?

Create Table A ( ID varchar(8), Primary Key(ID) ); Create Table B ( ID varchar(8), A_ID varchar(8), Primary Key(ID), Foreign Key(A_ID) References A(ID) ); 

Given that I created two tables using the above SQL statements, and I want to create Entity classes for them, for class B I have these element attributes:

 @Id @Column(name = "ID", nullable = false, length = 8) private String id; @JoinColumn(name = "A_ID", referencedColumnName = "ID", nullable = false) @ManyToOne(optional = false) private A AId; 

In class A do I need to perform a mutual relationship?

 @Id @Column(name = "ID", nullable = false, length = 8) private String id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "AId") private List<B> BList; //<-- Is this attribute necessary? 

Is it necessary or desirable to have a reverse @OneToMany for @ManyToOne ? If I make a design decision to leave the @OneToMany annotated attribute, will it come back to bite me again?

+7
java orm jpa persistence
source share
2 answers

Is it a necessity or a good idea to have the opposite of @OneToMany for @ManyToOne?

No, this is not necessary, it is a pure design decision. The whole question is this: do you want this (i.e. unidirectional communication):

uni-directional

Or this (i.e., bi-directional association):

bi-directional

If you do not need to get Bs from A, you can skip the bs and OneToMany on side A.

If I make a design decision to leave now the annotated attribute @OneToMany, will come back to bite me further.

No, and you can add it later if you find that you need it.

+11
source share

They are optional. There is no need to add them to your model if you do not want to use them.

I would advise avoiding backward matching at all, because such collections can become quite large, and most layers of resilience fail to cope with these very good ones. In many cases, you will have to deal with adding / deleting already loaded / managed objects associated with these collections. Therefore, add them only if they really make your task easier.

+2
source share

All Articles