I have 2 test classes:
Class A{
B b;
// some other properties
}
Class B{
// some properties
}
every instance of A has only one instance of class B, but an instance of class B can be assigned to more than one instance of class A
like :
B b = new B();
A a1 = new A();
a1.setB(b);
A a2 = new A();
a2.setB(b);
what type of association is this?
At first I was thinking about a one-to-one unidirectional but maybe is a many-to-one? but I don’t have any collection of A objects on B.
Can someone explain me what is the correct way to implements this association (using annotation)?
So , A to B is the many-to-one relationship . B to A is the one-to-many relationship.
The following shows the bi-directional mapping between A and B using annotation:
Important points:
@Entitymarks the java class as an hibernate entity. It is mapped to the name of the table specified in the@TableIf no
@Tableis specified ,by default , it is mapped to the table with the name that is equal to the unqualified class name of the entity.@ManyToOnedefines Class A to Class B ‘s relationship is many-to-oneIn the relational database , one-to-many relationship is expressed by using the following foreign key constraint :
“Many side table” has a FK column which only accepts the PK of the “one side table”.
This name of this FK column can be defined explictly by the
nameattribute of@JoinColumn. If@JoinColumnis not specified , then default value(s) with be used for this FK column , which concatenates with the name of “one side table”, _ (underscore), and the name of the PK in the “one side table”.@OneToManydefines Class B to Class A ‘s relationship is one-to-many.