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` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

CREATE TABLE `players` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `lastname` varchar(20) NOT NULL,
  `team_id` int(6) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `player's team` (`team_id`),
  CONSTRAINT `player's team` FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

The next step is creation of POJOs:

import java.util.Set;

import javax.persistence.*;

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

	@Id
	@GeneratedValue
	private Integer id;

	private String name;

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

          players;

	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.*;

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

	@Id
	@GeneratedValue
	private Integer id;

	private String lastname;

	@ManyToOne
	@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();
		session.beginTransaction();

		Team team = new Team('Barcelona');
		Set

          players = new HashSet

          ();

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

		p1.setTeam(team);
		p2.setTeam(team);

		players.add(p1);
		players.add(p2);

		team.setPlayers(players);

		session.save(team);

		session.getTransaction().commit();

		session.close();

	}
...

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

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

  1. Alex says:

    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. 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:

    http://stackoverflow.com/questions/24673798/spring-mvc-hibernate-a-form-with-checkboxes-for-manytomany-relationship/24701007#24701007

Leave a Reply


− one = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close