hibernate多对多注解式开发
程序员文章站
2022-04-14 21:53:44
...
@Entity //实体
@Table(name = "Game") //表名
public class Game {
@Id //指定主键
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sql_Game") //主键生成策略
@SequenceGenerator(name="sql_Game",sequenceName = "sql_Game",allocationSize = 1,initialValue = 1) //声明主键的生成策略
private Integer gid;
@Column
private String gname;
@ManyToMany(cascade = CascadeType.ALL) //指定多对多的关系,同时设置级联
//制定第三张表,指定本表与中间表的外键对应,另一张表与第三张表的外键的对应关系
@JoinTable(name="PG",joinColumns = {@JoinColumn(name = "gid")},inverseJoinColumns = {@JoinColumn(name = "pid")})
private Set<Player> player=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> getPlayer() {
return player;
}
public void setPlayer(Set<Player> player) {
this.player = player;
}
}
@Entity
@Table(name = "Player")
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sql_Play")
@SequenceGenerator(name="sql_Play",sequenceName = "sql_Play",allocationSize = 1,initialValue = 1)
private Integer pid;
@Column
private String pname;
@ManyToMany(cascade = CascadeType.ALL,mappedBy = "player")
private Set<Game> game=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> getGame() {
return game;
}
public void setGame(Set<Game> game) {
this.game = game;
}
}
@Test
public void test01(){
Game game1=new Game();
game1.setGname("CS");
Game game2=new Game();
game2.setGname("C#");
Player player1=new Player();
player1.setPname("吃鸡");
Player player2=new Player();
player2.setPname("王者荣耀");
game1.getPlayer().add(player1);
game1.getPlayer().add(player2);
game2.getPlayer().add(player1);
game2.getPlayer().add(player2);
player1.getGame().add(game1);
player1.getGame().add(game2);
player2.getGame().add(game1);
player2.getGame().add(game2);
session.save(game1);
session.save(game2);
tx.commit();
System.out.println("ok!");
}
只需要在主表做级连就可以了,上面的代码只是简单的测试 。
上一篇: HTML CSS的中英文对照
下一篇: Oracle数据库,简单SQL练习与答案