Issue
I am learning hibernate and trying to understand how to establish the relationship between two entities (OneToOne
, OneToMany
, ManyToMany
). Consider the simple scenario:
User Entity:
@Entity
class User {
@Id
private userId;
private Vehicle vehicle;
// other code
}
Vehicle Entity:
@Entity
public class Vehicle {
@Id
private int vehicleId;
private String desc;
// other code
}
My aim is to specify:
One to Many relationship
or One to one
relationship between User
and Vehicle
entities.
I know there are OneToOne
, OneToMany
annotations, but I not able to understand how is this relationship interpreted? Does it depend in which Entity the other Entity is placed?
For example:
@Entity
class User {
@Id
private userId;
private Vehicle vehicle;
// other code
}
As we can see, I have placed the Vehicle
entity inside the User
entity and if I use OneToMany
annotation on top of Vehicle
entity, does it mean 1:M relationship between User
-> Vehicle
entity.
Can anyone help me understand this?
Solution
I'll make this an answer to explain better but keep in mind that these are really the basic of hibernate mappings and you can probably read them up in any tutorial online.
With User table being:
userId userName etc
and Vehicle table being
vehicleId userIdFK etc
it is an obvious one many relationship: one user more vehicle.
To map this relationship you have
@Entity
class User {
@Id
private userId;
private String userName
// other code
}
and
@Entity
pubic class Vehicle {
@Id
private int vehicleId;
private String desc;
@ManyToOne
@JoinColumn(name = "userIdFK", referencedColumnName = "userId")
private User user;
// other code
}
This is what it's know as a unidirectional mapping where you have just the essential to let hibernate know of the presence of the FK on the db
@ManyToOne to specify the type of relationship (one vehicle is of one user)
While @JoinColumn is used to say "hey hibernate Vehicle table has a FK towards User table" with the name and referencedColumnName being the db column name involved in the Fk.
If you want you can make the relayionship as Bidirectional which is useful sometimes where you add a reference from the not-owning side of the association (in this case from user to vehicle)so you can get from both class to the other
@Entity
class User {
@Id
private userId;
private String userName
@OneToMany(mappedBy = "user")
private List<Vehicle> vehicleList;
// other code
}
MappedBy must specify the other field mapping the relationship
Answered By - Zeromus
Answer Checked By - David Goodson (JavaFixing Volunteer)