spring data jpa單個模型(單個表)分頁
阿新 • • 發佈:2019-02-12
1. 有模型MacBook
2. 在MacbookService中呼叫分頁的方法
3. 模型的程式碼
import java.util.Date; public class MacBook { private Integer id; private String name; private Long price; private Date createTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getPrice() { return price; } public void setPrice(Long price) { this.price = price; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
4. dao的程式碼
import java.util.Date; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.apache.commons.lang.StringUtils; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface MacbookDAO extends JpaRepository<MacBook, Long>, JpaSpecificationExecutor<MacBook> { public class QuerySpecification { public static Specification<MacBook> querySpecification(final MacBook mac) { return new Specification<MacBook>() { @Override public Predicate toPredicate(Root<MacBook> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate predicate = cb.conjunction(); if (StringUtils.isNotBlank(mac.getName())) { predicate.getExpressions().add(cb.like(root.<String>get("name"), "%" + StringUtils.trim(mac.getName()) + "%")); } if (mac.getPrice() != null&&mac.getPrice()!=0) { predicate.getExpressions().add(cb.equal(root.get("price").as(Long.class), mac.getPrice())); } query.orderBy(cb.desc(root.get("createTime").as(Date.class))); return predicate; } }; } } }
5. service的程式碼
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class MacbookService { @Autowired private MacbookDAO macbookDAO; public Page<MacBook> pageList(String name) { MacBook mac = new MacBook(); mac.setName(name); Pageable pageable = new PageRequest(0, 10);//第一頁,每一頁10個 Page<MacBook> jpaPage = macbookDAO.findAll(MacbookDAO.QuerySpecification.querySpecification(mac), pageable); return jpaPage; } }