【问题标题】:Create Spring Data Jpa Specification method without JOINS创建没有 JOINS 的 Spring Data Jpa Specification 方法
【发布时间】:2020-08-01 11:28:39
【问题描述】:

我有一个Spring-MVC 在线商店项目,我使用Spring BootHibernate。我决定使用Specification 进行过滤。因此,我使用 JOINS 为规范编写了一个方法。请告诉我如何在没有 JOIN 的情况下编写相同的方法。

TeaSpecification 类:

public static Specification<Tea> getTeasByFilter(Long colorId, Long typeId, Long countryId) {
        return (root, query, criteriaBuilder) -> {
            Join<Object, Object> colorJoin = root.join(Tea_.TEA_COLOR);
            Join<Object, Object> typeJoin = root.join(Tea_.TEA_TYPE);
            Join<Object, Object> countryJoin = root.join(Tea_.COUNTRIES);
            Predicate countryPredicate = criteriaBuilder.equal(countryJoin.get(Countries_.ID), countryId);
            Predicate colorPredicate = criteriaBuilder.equal(colorJoin.get(TeaColor_.ID), colorId);
            Predicate typePredicate = criteriaBuilder.equal(typeJoin.get(TeaColor_.ID), typeId);
            return criteriaBuilder.and(colorPredicate, typePredicate, countryPredicate);
        };
    }

饮料类(茶扩展饮料):

@Inheritance(strategy = InheritanceType.JOINED)
public class Drink {

    // Fields
    //
    private @Id
    @GeneratedValue
    Long id;

    private String name;

    private BigDecimal price;

    private String about;

    @Column(name = "is_deleted")
    private boolean isDeleted;

    // Relationships
    //
    @ManyToOne
    @JoinColumn(name = "packaging_id")
    private Packaging packaging;

    @ManyToOne
    @JoinColumn(name = "manufacturer_id")
    private Manufacturer manufacturer;

    @ManyToOne
    @JoinColumn(name = "country_id")
    private Countries countries;
}
public class Tea extends Drink {

    // Relationships
    //
    @ManyToOne
    @JoinColumn(name = "type_id")
    private TeaType teaType;

    @ManyToOne
    @JoinColumn(name = "color_id")
    private TeaColor teaColor;
}

【问题讨论】:

    标签: java hibernate spring-mvc spring-data-jpa specifications


    【解决方案1】:
    public class TeaSpecification {
    
        public static Specification<Tea> getTeasByFilter(Long colorId, Long typeId, Long countryId) {
            return (root, query, criteriaBuilder) -> {
                Predicate colorPredicate = criteriaBuilder
                        .equal(root.get(Tea_.teaColor).get(TeaColor_.id), colorId);
                Predicate typePredicate = criteriaBuilder
                        .equal(root.get(Tea_.teaType).get(TeaType_.id), typeId);
                Predicate countryPredicate = criteriaBuilder
                        .equal(root.get(Tea_.countries).get(Countries_.id), countryId);
                return criteriaBuilder.and(colorPredicate, typePredicate, countryPredicate);
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2019-02-03
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多