JPA关系映射之many-to-many

@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表实体类

 @Entity
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name="t_user")
public class User extends BaseDomain { private int userId;
private Set<Board> manBoards=new HashSet<Board>(); @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
public int getUserId() {
return userId;
} public void setUserId(int userId) {
this.userId = userId;
} @ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST},fetch=FetchType.EAGER)
@JoinTable(name="t_board_manager",joinColumns={@JoinColumn(name="user_id")},inverseJoinColumns={@JoinColumn(name="board_id")})
public Set<Board> getManBoards() {
return manBoards;
} public void setManBoards(Set<Board> manBoards) {
this.manBoards = manBoards;
} }

User和Board是多对多映射关系,用@ManyToMany注释标注。

在Board类中指定我们这个users的集合是映射到User类里面的manBoards属性列。

在User中用@JoinTable指定中间表,并为该表添加了相关列,其中joinColumns添加该属性所在User表中的主键user_id,inverseJoinColumns添加Board表中的主键board_id。

上一篇:JPA关系映射之one-to-many和many-to-one


下一篇:[Z]Spring Data JPA 之 一对一,一对多,多对多 关系映射