BIDIRECTIONAL @ONETOMANY / @MANYTOONE ASSOCIATION

来源:互联网 发布:linux配置ant 编辑:程序博客网 时间:2024/05/21 06:47

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:

view plaincopy to clipboardprint?
  1. CREATE TABLE `teams` (  
  2.   `id` int(6) NOT NULL AUTO_INCREMENT,  
  3.   `namevarchar(20) NOT NULL,  
  4.   PRIMARY KEY (`id`)  
  5. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;  
  6.   
  7. CREATE TABLE `players` (  
  8.   `id` int(6) NOT NULL AUTO_INCREMENT,  
  9.   `lastname` varchar(20) NOT NULL,  
  10.   `team_id` int(6) NOT NULL,  
  11.   PRIMARY KEY (`id`),  
  12.   KEY `player's team` (`team_id`), 
  13.   CONSTRAINT `player's team` FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`) ON DELETE CASCADE ON UPDATE CASCADE  
  14. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;  

The next step is creation of POJOs:

view plaincopy to clipboardprint?
  1. import java.util.Set;  
  2.   
  3. import javax.persistence.*;  
  4.   
  5. @Entity  
  6. @Table(name = "teams")  
  7. public class Team {  
  8.   
  9.     @Id  
  10.     @GeneratedValue  
  11.     private Integer id;  
  12.       
  13.     private String name;  
  14.       
  15.     @OneToMany(mappedBy="team", cascade=CascadeType.ALL)  
  16.     private Set<player> players;  
  17.       
  18.     public Team(String name) {  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public Integer getId() {  
  23.         return id;  
  24.     }  
  25.   
  26.     public void setId(Integer id) {  
  27.         this.id = id;  
  28.     }  
  29.   
  30.     public String getName() {  
  31.         return name;  
  32.     }  
  33.   
  34.     public void setName(String name) {  
  35.         this.name = name;  
  36.     }  
  37.   
  38.     public Set<player> getPlayers() {  
  39.         return players;  
  40.     }  
  41.   
  42.     public void setPlayers(Set<player> players) {  
  43.         this.players = players;  
  44.     }  
  45. }  
  46. </player></player></player>  

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.

view plaincopy to clipboardprint?
  1. import javax.persistence.*;  
  2.   
  3. @Entity  
  4. @Table(name = "players")  
  5. public class Player {  
  6.   
  7.     @Id  
  8.     @GeneratedValue  
  9.     private Integer id;  
  10.   
  11.     private String lastname;  
  12.   
  13.     @ManyToOne  
  14.     @JoinColumn(name = "team_id")  
  15.     private Team team;  
  16.   
  17.     public Player(String lastname) {  
  18.         this.lastname = lastname;  
  19.     }  
  20.   
  21.     public Integer getId() {  
  22.         return id;  
  23.     }  
  24.   
  25.     public void setId(Integer id) {  
  26.         this.id = id;  
  27.     }  
  28.   
  29.     public String getLastname() {  
  30.         return lastname;  
  31.     }  
  32.   
  33.     public void setLastname(String lastname) {  
  34.         this.lastname = lastname;  
  35.     }  
  36.   
  37.     public Team getTeam() {  
  38.         return team;  
  39.     }  
  40.   
  41.     public void setTeam(Team team) {  
  42.         this.team = team;  
  43.     }  
  44. }  

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:

view plaincopy to clipboardprint?
  1. ...  
  2.     public static void main(String[] args) {  
  3.   
  4.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
  5.         Session session = sessionFactory.openSession();  
  6.         session.beginTransaction();  
  7.           
  8.         Team team = new Team("Barcelona");  
  9.         Set<player> players = new HashSet<player>();  
  10.           
  11.         Player p1 = new Player("Messi");  
  12.         Player p2 = new Player("Xavi");  
  13.           
  14.         p1.setTeam(team);  
  15.         p2.setTeam(team);  
  16.           
  17.         players.add(p1);  
  18.         players.add(p2);  
  19.           
  20.         team.setPlayers(players);  
  21.           
  22.         session.save(team);  
  23.           
  24.         session.getTransaction().commit();  
  25.           
  26.         session.close();  
  27.   
  28.     }  
  29. ...  
  30. </player></player>  

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.

0 0
原创粉丝点击