Alexey Zvolinskiy

About 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) { = name;

	public Integer getId() {
		return id;

	public void setId(Integer id) { = id;

	public String getName() {
		return name;

	public void setName(String 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) { = id;

	public String getLastname() {
		return lastname;

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

	public Team getTeam() {
		return team;

	public void setTeam(Team 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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

3 Responses to "Bidirectional @OneToMany / @ManyToOne association"

  1. Alex says:


    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. lethal.industry says:

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

  3. lethal.industry says:

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

Leave a Reply

3 − = zero

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books