JPA单向多对多实体映射

知识点梳理:

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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值