@ManyToMany
Board表实体类
@Entity @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Table(name="t_board") public class Board extends BaseDomain { private int boardId; private Set<User> users=new HashSet<User>(); @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="board_id") public int getBoardId() { return boardId; } public void setBoardId(int boardId) { this.boardId = boardId; } @ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE}, mappedBy = "manBoards", fetch = FetchType.LAZY) public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
User表实体类
1 @Entity 2 @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 3 @Table(name="t_user") 4 public class User extends BaseDomain { 5 6 private int userId; 7 private Set<Board> manBoards=new HashSet<Board>(); 8 9 @Id 10 @GeneratedValue(strategy = GenerationType.IDENTITY) 11 @Column(name = "user_id") 12 public int getUserId() { 13 return userId; 14 } 15 16 public void setUserId(int userId) { 17 this.userId = userId; 18 } 19 20 @ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST},fetch=FetchType.EAGER) 21 @JoinTable(name="t_board_manager",joinColumns={@JoinColumn(name="user_id")},inverseJoinColumns={@JoinColumn(name="board_id")}) 22 public Set<Board> getManBoards() { 23 return manBoards; 24 } 25 26 public void setManBoards(Set<Board> manBoards) { 27 this.manBoards = manBoards; 28 } 29 30 }
User和Board是多对多映射关系,用@ManyToMany注释标注。
在Board类中指定我们这个users的集合是映射到User类里面的manBoards属性列。
在User中用@JoinTable指定中间表,并为该表添加了相关列,其中joinColumns添加该属性所在User表中的主键user_id,inverseJoinColumns添加Board表中的主键board_id。
时间: 2024-11-03 22:37:56