成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

Spring中如何定義Range范圍對(duì)象

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Spring中如何定義Range范圍對(duì)象,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供瓜州網(wǎng)站建設(shè)、瓜州做網(wǎng)站、瓜州網(wǎng)站設(shè)計(jì)、瓜州網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、瓜州企業(yè)網(wǎng)站模板建站服務(wù),十余年瓜州做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。

1 實(shí)現(xiàn)方式

1.1 范圍對(duì)象Range定義

import java.io.Serializable;


public class Range<E> 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<E> 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<T> implements Specification<T> {
  private final Example<T> example;

  public ByExampleSpecification(Example<T> example) {

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


  @Override
  public Predicate toPredicate(Root<T> root, CriteriaQuery<&#63;> 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<T> implements Specification<T> {
  private final List<Range<T>> ranges;

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

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

    for (Range<T> 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() &#63; builder.conjunction() : builder.and(toArray(predicates, Predicate.class));
  }

  private Predicate buildRangePredicate(Range<T> range, Root<T> 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與實(shí)現(xiàn)

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<E, PK extends Serializable> extends JpaRepository<E, PK> {


 Page<E> queryByExampleWithRange(Example example,List<Range<E>> 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<E, PK extends Serializable> extends SimpleJpaRepository<E, PK> implements
    WiselyRepository<E, PK> {
  private final EntityManager entityManager;

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



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

2 使用方式

2.1 開啟支持

通過@EnableJpaRepositories(repositoryBaseClass = WiselyRepositoryImpl.class)開啟對(duì)定義功能的支持。

2.2 示例

實(shí)體類

@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<Person,Long> {
}

測試控制器

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

  @Autowired
  PersonRepository personRepository;

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


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

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

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

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

  }
}

上述就是小編為大家分享的Spring中如何定義Range范圍對(duì)象了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

本文標(biāo)題:Spring中如何定義Range范圍對(duì)象
本文來源:http://jinyejixie.com/article6/ppehog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、品牌網(wǎng)站建設(shè)App開發(fā)、網(wǎng)站制作、標(biāo)簽優(yōu)化關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)
桑日县| 报价| 威远县| 和硕县| 南汇区| 伊川县| 娄烦县| 乌苏市| 宁蒗| 洱源县| 郸城县| 锡林浩特市| 安化县| 泗洪县| 靖边县| 连江县| 平乐县| 榆树市| 晋江市| 永宁县| 乌拉特中旗| 加查县| 时尚| 盘锦市| 苍溪县| 喀什市| 嘉善县| 旌德县| 桐柏县| 潜江市| 洪湖市| 安乡县| 尤溪县| 额尔古纳市| 土默特右旗| 衡东县| 黄石市| 建德市| 西乌| 山丹县| 曲阜市|