Java Hibernate实体列表@AssociationOverrides的映射列表

时间:2017-12-11 16:21:35

标签: java hibernate mapping

您好我有3个实体。

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    ...

    private List<BC> bcList;
}

@Entity
public class B {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    ...

}

@Entity
public class C {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    ...
}

这些实体由ManyToMany关联相互链接。这意味着我需要一个看起来像a_b_c( id_a,id_b,id_c )的关联表。 所以我创建了一个完全符合我想要的AssociationOverrides。

@Embeddable
public class ABCPK implements Serializable {


    @ManyToOne
    @JoinColumn(name = "id_a")
    private A a;

    @ManyToOne
    @JoinColumn(name = "id_b")
    private B b;

    @ManyToOne
    @JoinColumn(name = "id_c")
    private C c;
    ...
}

@Entity
@Table(name = "a_b_c")
@AssociationOverrides({
        @AssociationOverride(name = "pk.a",
                joinColumns = @JoinColumn(name = "id_a",referencedColumnName = "id")),
        @AssociationOverride(name = "pk.b",
                joinColumns = @JoinColumn(name = "id_b",referencedColumnName = "id")) ,
        @AssociationOverride(name = "pk.c",
                joinColumns = @JoinColumn(name = "id_c",referencedColumnName = "id")) })
public class ABC{

    @EmbeddedId
    private ABCPK pk=new ABCPK();

    @Transient
    public A getA() {
        return pk.getA();
    }

    public void setA(A a) {
        this.pk.setA(a);
    }
    ...


}

public class BC{
    private B b;
    private List<C> cList;
}

但是我想从我的关联表中检索List bcList和List cList,但我真的不知道怎么能这样做。我已经尝试过@JoinFormula但我更喜欢只使用jpql。你能帮我说对了吗? 感谢

1 个答案:

答案 0 :(得分:0)

由于我没有得到任何帮助,我已经下定决心自己填充我的地图并在持续更新之前重新填充abcList。但是我真的不喜欢这样,因为它不是性能和内存友好。 (abcList中约1 * 20 * 70项)

@Entity
public class A {
  ...
    @OneToMany
    private List<ABC> abcList;
    private Map<B,List<C>> bcMap;

    private Map<B,List<C>> buildBCmap(){
        bcMap  = new HashMap<>();
        if(abcList!=null){
            for(ABC abc:abcList){
                if(! bcMap.containsKey(abc.getB()){
                    bcMap.put(abc.getB(),new ArrayList<>());
                }   
                bcMap.get(abc.getB()).add(abc.getC());
            }
        }
        return bcMap;
    }

    public Map<B,List<C>> getBcMap(){
        if(bcMap==null){
            buildBCmap();
        }
        return bcMap;
    }

    @PrePersist
    @PreUpdate
    public void buildAbcList(){
        if(bcMap!=null){
            abcList=new ArrayList<>();
            for(B b: bcMap.keySet()){
                for(C c: bcMap.get(b)){
                    abcList.add(new ABC(this,b,c));
                }
            }
        }

    }
}

有没有人有更好或更快的方法从associationOverride实体填充地图?