Home » Java » Enterprise Java » Bidirectional @OneToMany / @ManyToOne association

About Alexey Zvolinskiy

Alexey Zvolinskiy
Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Bidirectional @OneToMany / @ManyToOne association

One of goals in programming is representing of models from real world. Very often an application need to model some relationship between entities. In the last article about Hibernate associations I have described rules of setting up the “one to one” relationship. Today I’m going to show you how to setup bidirectional “one to many” and “many to one” association. This example will be based on previous Hibernate tutorials.

At the start I need to say that my code example will be based on a simple situation. Let’s imagine a football league. Every league has teams, and in the team can play some players. So the summary is following: one team has many players, one player can play for an one team. In this way we get obvious “one to many” and “many to one” relationships.

I use MySQL as a database in this example. Here are scripts for the tables creation:

CREATE TABLE `teams` (
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)

CREATE TABLE `players` (
  `lastname` varchar(20) NOT NULL,
  `team_id` int(6) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `player's team` (`team_id`),

The next step is creation of POJOs:

import java.util.Set;

import javax.persistence.*;

@Table(name = 'teams')
public class Team {

	private Integer id;

	private String name;

	@OneToMany(mappedBy='team', cascade=CascadeType.ALL)
	private Set


	public Team(String name) {
		this.name = name;

	public Integer getId() {
		return id;

	public void setId(Integer id) {
		this.id = id;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public Set

           getPlayers() {
		return players;

	public void setPlayers(Set

            players) {
		this.players = players;

I have used @OneToMany because one team can has many players. In the next POJO, association will be @ManyToOne since many players can play for an one team.

import javax.persistence.*;

@Table(name = 'players')
public class Player {

	private Integer id;

	private String lastname;

	@JoinColumn(name = 'team_id')
	private Team team;

	public Player(String lastname) {
		this.lastname = lastname;

	public Integer getId() {
		return id;

	public void setId(Integer id) {
		this.id = id;

	public String getLastname() {
		return lastname;

	public void setLastname(String lastname) {
		this.lastname = lastname;

	public Team getTeam() {
		return team;

	public void setTeam(Team team) {
		this.team = team;

Here I specify the column (team_id) which will be joined from the owning side (Teams). Notice that I don’t declare team_id field in the POJO. If I need to change a team for a player I just need to use setTeam(Team team) setter.

After POJOs were declared, I can demonstrate how to persist them:

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		Team team = new Team('Barcelona');

          players = new HashSet


		Player p1 = new Player('Messi');
		Player p2 = new Player('Xavi');








The result of the code execution is:

Hibernate: insert into teams (name) values (?)
Hibernate: insert into players (lastname, team_id) values (?, ?)
Hibernate: insert into players (lastname, team_id) values (?, ?)

That’s it, in this tutorial I have demonstrated how to setup “one to many” and “many to one” bidirectional association. I don’t see any sense in a same tutorial with an example of unidirectional association. Because Hibernate has its own best practices:

Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.


Reference: Bidirectional @OneToMany / @ManyToOne association from our JCG partner Alex Fruzenshtein at the Fruzenshtein’s notes blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....



  1. Hi,

    Assuming I have a situation like this:

    Employee belongs to a Department.
    Department belongs to a Division.

    Department and Division have a manager which is of type Employee.

    I am not interested in having access to employees from Department (In the owner side storing a list of Employees)

  2. where can i find an example / tutorial for a form with checboxes of a many-to-many or one-to-many relationship?

  3. i implemented this solution (not the best, but it works)… i post this so maybe someone can find it usefull:


Leave a Reply

Your email address will not be published. Required fields are marked *


1 + = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.