Hibernate One-To-Many Mapping

A one-to-many relationship occurs when one entity is related to many occurrences in another entity.Consider the following relationship between UserDetails Class and Vehicle entity.
One user have the multiple vehicles.
Class diagram for that given below.
In this example UserDetails class has the collection of the another entity class Vehicle. So the given below diagram so table structure for that.

For that we will use the following annotation.
@OneToMany:
Target:
Fields (including property get methods)
Defines a many-valued association with one-to-many multiplicity. If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.
The OneToMany annotation may be used within an embeddable class contained within an entity class to specify a relationship to a collection of entities. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.
@Entity
@Table (name=”USER”)

public class UserDetails
{
@Id
@Column(name=”USER_ID”)
@GeneratedValue(strategy=GenerationType.AUTO)

private int    userId;

@Column(name=”USER_NAME”)
private String userName;

@OneToMany
@JoinTable( name=”USER_VEHICLE”,
joinColumns=@JoinColumn(name=”USER_ID”),
inverseJoinColumns=@JoinColumn(name=”VEHICLE_ID”))
//its optional using for name configuration of the join table
private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();

public int getUserId() {
return userId;
}
public Collection<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(Collection<Vehicle> vehicle) {
this.vehicle = vehicle;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s