One of goals the in programming is representation of models from the real world. Very often an application needs to model some relationship between entities. In the last article about Hibernate associations I described the rules of setting up a “one to one” relationship. Today I’m going to show you how to setup a 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 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 table’s 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<Player> 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<Player> getPlayers() {
		return players;
	}

	public void setPlayers(Set<Player> players) {
		this.players = players;
	}
}

I have used @OneToMany because one team can have many players. In the next POJO, the association will be @ManyToOne since many players can play for 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<Player> players = new HashSet<Player>();
		
		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 the 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.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close