Hibernate : Mapping object associations

Suppose there are two persistent classes called A and B. The relationship of A and
B is called one-to-one if any instance of A is associated with only a single instance
of B, and no more. A one-to-one association is always presented as an instance of B
defined as a property of A, or vice versa.

The association is called one-to-many from A to B if any instance of A can be
associated with more than one instance of B. This relationship is established by a
property of a collection type of B instances in class A. The one-to-many relationship
from A to B is called many-to-one when going from B to A. In other words, when
more than one instance of B can be associated with one instance of A.

The final type of relationship, which is rare, is many-to-many: more than one
instance of A can be associated with more than one instance of B. In this
relationship, each instance of A holds a collection of B instances, and vice versa.


Two persistent classes may be associated with each other in a one-to-one
relationship. A relationship is called one-to-one when each instance of a class
is associated with a single instance of another class, and vice versa. If, when you
have an instance of one class, and the other instance can be reached, then the
one-to-one relationship is called bidirectional. On the other hand, if the objects
cannot be reached from both sides, the relationship is unidirectional.

  • Using identical primary keys
  • 	// unidirectional
    	public class Student {
    	private int id;
    	private Phone phone;
    	//other fields and getter/setter methods
    // bidirectional public class Phone { @OneToOne(mappedBy="student") // mappedBy=<propert name> private Student student; }
  • Foreign key one-to-one
  • 	public class Student {
    	private Phone phone;


public class Student {
	private Address address;


public class School {
	@OneToMany(mappedBy = "school")
	private List students = new ArrayList();

// ManyToOne annotation is used to map the reverse side of the one-to-many relationship public class Student { @ManyToOne @JoinColumn(name = "SCHOOL_ID") private School school; }


	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
	public Set getCourses() { // or List
		return courses;

@Entity @Table(name = "COURSE") public class Course { @Id @GeneratedValue @Column(name = "ID") public int getId() { return id; } }

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: