查询以空元素联接

时间:2019-02-03 21:55:45

标签: sql hibernate jpa

我在休眠状态下使用spring数据jpa。

@Entity
public class Samples {

    @EmbeddedId
    private SampleId id;

    @MapsId("samplingId")
    @ManyToOne(optional = false)
    private Samplings sampling;
    ..
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings {
    @OneToOne
    private Products product;

    @OneToOne
    private Dimensions dimension;

    @OneToOne
    private Colors color;
    ...
}

尺寸和颜色可以为空。

我搜索以samplesproductdimensions来获得colors(如果没有dimensioncolors,也获得samples

我做到了:

Join<Samples, Samplings> samplings = root.join("sampling", JoinType.INNER);
Join<Samples, Colors> colors = (Join) samplings.join("color", JoinType.INNER);
Join<Samples, Dimensions> dimension = (Join) samplings.join("dimension", JoinType.INNER);
Join<Samplings, Products> product = (Join) samplings.join("product", JoinType.INNER);

要获得结果,我需要为colordimension

1 个答案:

答案 0 :(得分:1)

  

如果没有尺寸,颜色,也想获取样品

要实现此目的,您需要将INNER JOINcolor上的dimension更改为LEFT JOIN s

Join<Samples, Samplings> samplings = root.join("sampling", JoinType.INNER);
Join<Samples, Colors> colors = (Join) samplings.join("color", JoinType.LEFT);
Join<Samples, Dimensions> dimension = (Join) samplings.join("dimension", JoinType.LEFT);
Join<Samplings, Products> product = (Join) samplings.join("product", JoinType.INNER);

根据您的用例,您可能还希望将INNER JOIN上的product转换为LEFT JOIN