资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Spring中如何定义Range范围对象

这期内容当中小编将会给大家带来有关Spring中如何定义Range范围对象,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

创新互联专业为企业提供瓜州网站建设、瓜州做网站、瓜州网站设计、瓜州网站制作等企业网站建设、网页设计与制作、瓜州企业网站模板建站服务,十余年瓜州做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

1 实现方式

1.1 范围对象Range定义

import java.io.Serializable;


public class Range implements Serializable {
  private static final long serialVersionUID = 1L;

  private String field;
  private Comparable from;
  private Comparable to;
  private Boolean includeNull;


  public Range(String field) {
    this.field = field;
  }


  public Range(String field, Comparable from, Comparable to) {
    this.field = field;
    this.from = from;
    this.to = to;
  }

  public Range(String field, Comparable from, Comparable to, Boolean includeNull) {
    this.field = field;
    this.from = from;
    this.to = to;
    this.includeNull = includeNull;
  }


  public Range(Range other) {
    this.field = other.getField();
    this.from = other.getFrom();
    this.to = other.getTo();
    this.includeNull = other.getIncludeNull();
  }

  public String getField() {
    return field;
  }

  public Comparable getFrom() {
    return from;
  }


  public void setFrom(Comparable from) {
    this.from = from;
  }

  public boolean isFromSet() {
    return getFrom() != null;
  }


  public Comparable getTo() {
    return to;
  }

  public void setTo(Comparable to) {
    this.to = to;
  }

  public boolean isToSet() {
    return getTo() != null;
  }

  public void setIncludeNull(boolean includeNull) {
    this.includeNull = includeNull;
  }

  public Boolean getIncludeNull() {
    return includeNull;
  }

  public boolean isIncludeNullSet() {
    return includeNull != null;
  }

  public boolean isBetween() {
    return isFromSet() && isToSet();
  }

  public boolean isSet() {
    return isFromSet() || isToSet() || isIncludeNullSet();
  }

  public boolean isValid() {
    if (isBetween()) {
      return getFrom().compareTo(getTo()) <= 0;
    }

    return true;
  }
}

1.2 example的Specification

import org.springframework.data.domain.Example;
import org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.Assert;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Created by wangyunfei on 2017/6/6.
 */
public class ByExampleSpecification implements Specification {
  private final Example example;

  public ByExampleSpecification(Example example) {

    Assert.notNull(example, "Example must not be null!");
    this.example = example;
  }


  @Override
  public Predicate toPredicate(Root root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    return QueryByExamplePredicateBuilder.getPredicate(root, cb, example);
  }
}

1.3 Range的Specification

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

import static com.google.common.collect.Iterables.toArray;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

/**
 * Created by wangyunfei on 2017/6/6.
 */
public class ByRangeSpecification implements Specification {
  private final List> ranges;

  public ByRangeSpecification(List> ranges) {
    this.ranges = ranges;
  }

  @Override
  public Predicate toPredicate(Root root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    List predicates = newArrayList();

    for (Range range : ranges) {
      if (range.isSet()) {
        Predicate rangePredicate = buildRangePredicate(range, root, builder);

        if (rangePredicate != null) {
          if (!range.isIncludeNullSet() || range.getIncludeNull() == FALSE) {
            predicates.add(rangePredicate);
          } else {
            predicates.add(builder.or(rangePredicate, builder.isNull(root.get(range.getField()))));
          }
        }

        if (TRUE == range.getIncludeNull()) {
          predicates.add(builder.isNull(root.get(range.getField())));
        } else if (FALSE == range.getIncludeNull()) {
          predicates.add(builder.isNotNull(root.get(range.getField())));
        }
      }
    }
    return predicates.isEmpty() ? builder.conjunction() : builder.and(toArray(predicates, Predicate.class));
  }

  private Predicate buildRangePredicate(Range range, Root root, CriteriaBuilder builder) {
    if (range.isBetween()) {
      return builder.between(root.get(range.getField()), range.getFrom(), range.getTo());
    } else if (range.isFromSet()) {
      return builder.greaterThanOrEqualTo(root.get(range.getField()), range.getFrom());
    } else if (range.isToSet()) {
      return builder.lessThanOrEqualTo(root.get(range.getField()), range.getTo());
    }
    return null;
  }

}

1.4 自定义Repository与实现

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import java.io.Serializable;
import java.util.List;

@NoRepositoryBean
public interface WiselyRepository extends JpaRepository {


 Page queryByExampleWithRange(Example example,List> ranges, Pageable pageable);

}
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.List;

import static org.springframework.data.jpa.domain.Specifications.where;


public class WiselyRepositoryImpl extends SimpleJpaRepository implements
    WiselyRepository {
  private final EntityManager entityManager;

  public WiselyRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
    super(entityInformation, entityManager);
    this.entityManager = entityManager;
  }



  @Override
  public Page queryByExampleWithRange(Example example, List> ranges, Pageable pageable) {
    Specification byExample = new ByExampleSpecification<>(example);
    Specification byRanges = new ByRangeSpecification<>(ranges);
    return findAll(where(byExample).and(byRanges),pageable);
  }
}

2 使用方式

2.1 开启支持

通过@EnableJpaRepositories(repositoryBaseClass = WiselyRepositoryImpl.class)开启对定义功能的支持。

2.2 示例

实体类

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private Integer height;
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Date birthday;
}

PersonRepository

public interface PersonRepository extends WiselyRepository {
}

测试控制器

@RestController
@RequestMapping("/people")
public class PersonController {

  @Autowired
  PersonRepository personRepository;

  @PostMapping
  public ResponseEntity save(@RequestBody Person person){
    Person p = personRepository.save(person);
    return new ResponseEntity(p, HttpStatus.CREATED);
  }


  @GetMapping
  public ResponseEntity> query(Person person,
                       @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate,
                       @DateTimeFormat(pattern = "yyyy-MM-dd")Date endDate,
                       Integer startHeight,
                       Integer endHeight,
                       Pageable pageable){
    Example personExample = Example.of(person);

    List> ranges = newArrayList();
    Range birthRange = new Range("birthday",startDate,endDate);
    Range heightRange = new Range("height",startHeight,endHeight);
    ranges.add(birthRange);
    ranges.add(heightRange);

    Page page = personRepository.queryByExampleWithRange(personExample,ranges,pageable);

    return new ResponseEntity>(page,HttpStatus.OK);

  }
}

上述就是小编为大家分享的Spring中如何定义Range范围对象了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


当前题目:Spring中如何定义Range范围对象
文章路径:http://cdkjz.cn/article/ppehog.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220