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);
}