使用JPA存储时,是否可以对重复的外键值进行分组?

时间:2019-04-25 22:34:57

标签: java mysql spring-boot jpa foreign-keys

在我的Spring Boot应用程序中,两个实体相互之间具有多对多关系,即父级和子级。我有一个异步处理器,它可以获取一些数据来构建和存储父母。当我遍历每个父对象并构建实体时,我也正在获取/构建子实体,并将与字段道具匹配的子实体映射到父对象。问题在于某些子实体对于多个父字段具有相同的字段值,因此当我在最后存储所有完整的父实体时,数据库的子表中有很多重复的字段值。有没有办法告诉JPA,应该将重复的Child.field值分组,并且Parent和Child之间的映射表应该指向正确的ID?

父实体:

@Entity
public class ParentEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "field")
    private String field;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
        name = "mapping",
        joinColumns = @JoinColumn(name = "parent_id"),
        inverseJoinColumns = @JoinColumn(name = "child_id"))
    private List<ChildEntity> children;

    public List<ChildEntity> getChildren() {
        return this.children
    }

    public void setChildren(List<ChildEntity> children){
        this.children = children
    }
}

还有我的孩子实体:

@Entity
public class ChildEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "field")
    private String field;

    @ManyToMany(mappedBy = "children")
    private List<ParentEntity> parents;

    public String getField() {
        return this.field;
    }    

    public List<ParentEntity> getParents() {
        return this.parents
    }

    public void setParents(List<ParentEntity> parents){
        this.parents = parents
    }
}

以及一些处理逻辑:

List<ParentEntity> parentList = new ArrayList<>();
someResponseData.forEach(d -> {
    ParentEntity parent = mapper.dataToParent(d);

    // children data coming from api call
    List<ChildEntity> children = someProcessor.buildChildrenByField(parent.getField());

    parent.setChildren(children);
    parentList.add(parent);
});
parentRepo.saveAll(parentList);

0 个答案:

没有答案