欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate关于多对多注解配置

程序员文章站 2022-04-14 21:35:11
...

Game实体类配置关系

@Entity
@Table(name = "game")
public class Game {
    @Id
    @GeneratedValue
    private Integer gid;
    private String gname;
    @ManyToMany(mappedBy = "games",cascade = CascadeType.ALL)
    private Set<Player> players=new HashSet<Player>();

    public Integer getGid() {
        return gid;
    }

    public void setGid(Integer gid) {
        this.gid = gid;
    }

    public String getGname() {
        return gname;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    public Set<Player> getPlayers() {
        return players;
    }

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

player实体类配置关系

@Entity
@Table(name = "player")
public class Player {
    @Id
    @GeneratedValue
    private Integer pid;
    private String pname;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "pg",joinColumns = @JoinColumn(name = "pid"),inverseJoinColumns = @JoinColumn(name = "gid"))
    private Set<Game> games=new HashSet<Game>();

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public Set<Game> getGames() {
        return games;
    }

    public void setGames(Set<Game> games) {
        this.games = games;
    }
}

hibernate.cfg.xml需要配置关联实体类路径

<mapping class="cn.wyd.a.Game"/>
		<mapping class="cn.wyd.a.Player"/>

测试类测试数据

 @Test
    public void test1() {
        Game game1 = new Game();
        Game game2 = new Game();
        game1.setGname("g1");
        game2.setGname("g2");
        Player player = new Player();
        player.setPname("123");
        player.getGames().add(game1);
        player.getGames().add(game2);
        game1.getPlayers().add(player);
        game2.getPlayers().add(player);
        session.save(player);
    }