知识点梳理:
a、注解配置时使用@JoinTable配置中间表,joinColumns配置当前类对应的主键ID,inverseJoinColumn反向配置对应的表主键ID
b、建表时,中间表配置双主键、双外键
1、建表
# 单向多对多
create table sys_role(
id varchar(64) primary key
,name varchar(50)
) engine InnoDB charset 'utf8';
create table sys_user(
id varchar(64) primary key
,name varchar(50)
)engine InnoDB charset 'utf8';
# 中间表
create table sys_role_user(
user_id varchar(64)
,role_id varchar(64)
, primary key (user_id, role_id)
, constraint fk_user_id_relative foreign key (user_id) references sys_user(id)
, constraint fk_role_id_relative foreign key (role_id) references sys_role(id)
) engine InnoDB charset 'utf8';
2、实体映射
@Entity
@Table(name = "sys_role")
@Setter
@Getter
public class Role {
@Id
@GeneratedValue(generator = "uid")
@GenericGenerator(name = "uid", strategy = "uuid")
private String id;
private String name;
public Role(String name){
this.name = name;
}
@Override
public String toString() {
return "{id:"+getId()+",name:"+getName()+"}";
}
}
@Entity
@Table(name = "sys_user")
@Setter
@Getter
public class User {
@Id
@GeneratedValue(generator = "uid")
@GenericGenerator(name = "uid", strategy = "uuid")
private String id;
private String name;
@ManyToMany
// 配置中间表的信息,name配置的是中间表的表名,
//joinColumns = @JoinColumn(name = "user_id"):配置的是当前user在中间表的列名
//inverseJoinColumns = @JoinColumn(name = "role_id"):配置的是role在中间表的列名
@JoinTable(name = "sys_role_user"
, joinColumns = @JoinColumn(name = "user_id")
, inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User(String name){
this.name = name;
}
@Override
public String toString() {
return "{id:"+getId()+",name:"+getName()+"}";
}
}
3、数据持久化
@Test
public void init(){
Role role1 = new Role("role01");
Role role2 = new Role("role02");
Role role3 = new Role("role03");
roleRepository.save(role1);
roleRepository.save(role2);
roleRepository.save(role3);
User user1 = new User("张三");
user1.getRoles().add(role1);
userRepository.save(user1);
User user2 = new User("李四");
user2.getRoles().add(role2);
user2.getRoles().add(role3);
userRepository.save(user2);
}