Bidirectional @OneToMany / @ManyToOne association

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值