hibernate的ManyToMany映射

hibernate的ManyToMany映射

1、前言

@ManyToMany指定了多对多的关系。

2、@ManyToMany单向多对多关联


Cat的单向关联

entity:Cat

@Entity
@Setter
@Getter
@Table(name = "jei_cat")
public class Cat implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @ApiModelProperty(value = "id")
    private Long id;

    @Column(name = "name")
    @ApiModelProperty(value = "昵称")
    private String name;

    @Column(name = "gender")
    @ApiModelProperty(value = "性别")
    private Integer gender;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "jei_cat_hobby",
            joinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")})
    private Set<Hobby> hobbys;

    public Set<HobbyDto> toHobbyDtos() {
        if (hobbys == null) {
            return null;
        }
        return hobbys.stream().map(x -> new HobbyDto(x.getId(), x.getHobby(), x.getExpression())).collect(Collectors.toSet());
    }
}

注意:

@JoinTable(name = "jei_cat_hobby",
joinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")})

这里joinColumns 表示当前表的关系,@JoinColumn()中name="cat_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段;

inverseJoinColumns 表示副表的关系,@JoinColumn()中name="hobby_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段。

Hobby单向关联

entity:Hobby

@Entity
@Setter
@Getter
@Table(name = "jei_hobby")
public class Hobby implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @ApiModelProperty(value = "id")
    private Long id;

    @Column(name = "hobby")
    @ApiModelProperty(value = "爱好")
    private String hobby;

    @Column(name = "expression")
    @ApiModelProperty(value = "表现")
    private String expression;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "jei_cat_hobby",
            joinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")})
    private Set<Cat> cats;
    
    public Set<CatDto> toCatDtos() {
        if (cats == null) {
            return null;
        }
        return cats.stream().map(x -> new CatDto(x.getId(), x.getName(), x.getGender())).collect(Collectors.toSet());
    }
}

注意:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "jei_cat_hobby",
joinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")})

这里joinColumns 表示当前表的关系,@JoinColumn()中name="hobby_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段;

inverseJoinColumns 表示副表的关系,@JoinColumn()中name="cat_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段。

双向关联

关联

entity:Cat

@Entity
@Setter
@Getter
@Table(name = "jei_cat")
public class Cat implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @ApiModelProperty(value = "id")
    private Long id;

    @Column(name = "name")
    @ApiModelProperty(value = "昵称")
    private String name;

    @Column(name = "gender")
    @ApiModelProperty(value = "性别")
    private Integer gender;

//    @ManyToMany(fetch = FetchType.LAZY)
//    @JoinTable(name = "jei_cat_hobby",
//            joinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")},
//            inverseJoinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")})
//    private Set<Hobby> hobbys;

    @ManyToMany(mappedBy = "cats")
    private List<Hobby> hobbys = new ArrayList<>();

}

注意:

@ManyToMany(mappedBy = "cats")

这里不再需要@JoinColumn进行声明关联,需要用mappedBy 来确定关系由谁来维护。mappedBy="cats"说明在两个关联的实体Bean中,hobby这一端是关系的拥有者。

@Entity
@Setter
@Getter
@Table(name = "jei_hobby")
public class Hobby implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @ApiModelProperty(value = "id")
    private Long id;

    @Column(name = "hobby")
    @ApiModelProperty(value = "爱好")
    private String hobby;

    @Column(name = "expression")
    @ApiModelProperty(value = "表现")
    private String expression;

    @ManyToMany
    @JoinTable(name = "jei_cat_hobby",
            joinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")})
    private List<Cat> cats = new ArrayList<>();
    
}

注意:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "jei_cat_hobby",
joinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "cat_id", referencedColumnName = "id")})

这里joinColumns 表示当前表的关系,@JoinColumn()中name="hobby_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段;

inverseJoinColumns 表示副表的关系,@JoinColumn()中name="cat_id"指关联表(MANY)中的字段, referencedColumnName = "id"指当前表(ONE)中的字段。

查询实例

查询cat

@Override
public ResponsePageVO<CatDto> queryAll(CatQueryCriteria criteria, Pageable pageable) {
    Page<Cat> page = catRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
    List<Cat> content = page.getContent();
    Map<Long, CatDto> collect = content.stream().map(x -> new CatDto(x.getId(), x.getName(), x.getGender(), hobbyMapper.toDto(x.getHobbys())))
            .collect(Collectors.toMap(item -> item.getId(), item -> item));
    return PageUtil.toPageVo(page.map(x -> collect.get(x.getId())));
}

查询hobby

@Override
public ResponsePageVO<HobbyDto> queryAll(HobbyQueryCriteria criteria, Pageable pageable) {
    Page<Hobby> page = hobbyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
    List<Hobby> content = page.getContent();
    Map<Long, HobbyDto> collect = content.stream().map(x -> new HobbyDto(x.getId(), x.getHobby(), x.getExpression(), catMapper.toDto(x.getCats())))
            .collect(Collectors.toMap(item -> item.getId(), item -> item));
    return PageUtil.toPageVo(page.map(x -> collect.get(x.getId())));
}
posted @   南翔技校毕业后  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示