加入和继承jpa

时间:2018-07-17 19:54:00

标签: hibernate jpa spring-data-jpa jpa-criteria

我将Spring数据,jpa与hibernate实现一起使用

我正在写高级搜索

public class Samples  extends BaseEntity{
    ..
    @Id
    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "sampling_id", referencedColumnName = "id"),
        @JoinColumn(name = "sampling_year", referencedColumnName = "year")})
    private Samplings sampling;
    ...
}

@Entity
@IdClass(SamplingsPK.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings extends  extends BaseEntity{
    @OneToOne
    private Products product;
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Products  extends BaseEntity{
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    private ProductTypes productType;
}

@Entity
@DiscriminatorValue("TraditionalProducts")
public class TraditionalProducts extends Products {
    ...
}

@Entity
@DiscriminatorValue("GranulateProducts")
public class GranulateProducts extends Products  {
     @ManyToMany(mappedBy="granulateProducts")
    private Set<Suppliers> suppliers = new HashSet<>();
}

@Entity
@DiscriminatorValue("GranulateSamplings")
public class GranulateSamplings extends Samplings{
    OneToOne(optional = true, fetch = FetchType.EAGER)
    @JoinColumn
    private Suppliers supplier;
    ...
}

和此搜索方法

 public Page<Samples> advancedSearch(SamplesSearchDto search, Pageable page) {
     Specification<Samples> specification = (Root<Samples> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {

         Predicate p = cb.conjunction();

         if (search.getProductsId() != null) {
             Join<Samples, Samplings> samplings = (Join) root.join("sampling");
             Join<Samples, Products> product = (Join) samplings.join("product");
             p.getExpressions().add(cb.equal(product.get("id"), search.getProductsId()));
         }

        if (search.getSuppliersId() != null) {
            Join<Samples, Samplings> samplings = (Join) root.join("sampling");
            Join<Samplings, Suppliers> supp = samplings.join("supplier");
            p.getExpressions().add(cb.equal(supp.get("id"), search.getSuppliersId()));
            //supplier name field is used in GranulateSamplings

        }

        return p;

    };

    return this.findAll(specification, page);
}

对于我的供应商现场搜索,我应该如何进行扩展产品的联接GranulateSamplings? 因为该字段仅在GranulateSamplings实体

中可用

编辑

我收到此错误

  

在此上无法找到具有给定名称[供应商]的属性   托管类型com.lcm.mode.Samplings

这就像无法独自完成抽样和供应商之间的桥梁

编辑

Join<Samples, Samplings> samplings = (Join) root.join("sampling");
Join<GranulateSamplings, Suppliers> supp = samplings.join("supplier");
p.getExpressions().add(cb.equal(supp.get("id"), search.getSuppliersId()));

同一问题

1 个答案:

答案 0 :(得分:0)

Join<Products, suppliers> supp = product.join("suppliers");
p.getExpressions().add(cb.equal(supp.get("id"), search.getSuppliersId()));

SuppliersId表示您有多个,只需迭代并添加您需要的所有等式

PD:类(尤其是实体)不应以复数形式命名