Bidirectional @OneToMany / @ManyToOne association
2015-09-08 10:57
471 查看
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:
The next step is creation of POJOs:
I have used
Here I specify the column (
After POJOs were declared, I can demonstrate how to persist them:
The result of the code execution is:
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 associa
c3e3
tions must be navigable in both directions in queries.
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
@OneToManybecause one team can have many players. In the next POJO, the association will be
@ManyToOnesince 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_idfield 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 associa
c3e3
tions must be navigable in both directions in queries.
相关文章推荐
- Hibernate Oracle sequence的使用技巧
- jsp Hibernate批量更新和批量删除处理代码
- jsp hibernate的分页代码第1/3页
- JAVA+Hibernate 无限级分类
- SSH整合中 hibernate托管给Spring得到SessionFactory
- jsp hibernate 数据保存操作的原理
- hibernate中的增删改查实现代码
- 解决hibernate+mysql写入数据库乱码
- java优化hibernate性能的几点建议
- java Hibernate延迟加载
- hibernate 常用方法介绍
- 深入理解Hibernate中的flush机制
- 解析使用jdbc,hibernate处理clob/blob字段的详解
- 浅析java程序中hibernate的应用总结
- java面试常见问题之Hibernate总结
- 关于Hibernate的一些学习心得总结
- Hibernate管理Session和批量操作分析
- 基于spring+hibernate+JQuery开发之电子相册(附源码下载)
- java Hibernate 一对多自身关联问题
- SpringMVC+MyBatis项目总结(二)