Reputation: 3640
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)?
Upvotes: 0
Views: 368
Reputation: 90417
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
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:
@Entity
@Table(name="tableA")
Class A{
@ManyToOne
@JoinColumn(name = "B_ID")
B b;
// some other properties
}
@Entity
@Table(name="tableB")
Class B{
@OneToMany(mappedBy = "b")
List Set<A> listOfA= new ArrayList<A>();
// some other properties
}
Important points:
@Entity
marks the java class as an hibernate entity. It is mapped to the name of the table specified in the @Table
If no @Table
is specified ,by default , it is mapped to the table with the name that is equal to the unqualified class name of the entity.
@ManyToOne
defines Class A to Class B 's relationship is many-to-one
In 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 name
attribute of @JoinColumn
. If @JoinColumn
is 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".
@OneToMany
defines Class B to Class A 's relationship is one-to-many.
Upvotes: 5