Spring JPA CriteriaBuilder 分页查询
Autowired。
package repository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import pojo.Product;
@Repository
public class ProductSearchRepository {
@Autowired
private EntityManager entityManager;
public List<Product> findProduct(String type, String name) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
Predicate pType=cb.equal(root.get("type"), type);
Predicate pName=cb.equal(root.get("name"),name);
Predicate pAnd=cb.and(pType,pName);
cq.where(pAnd);
List<Product> list = entityManager.createQuery(cq).getResultList();
return list;
}
public List<String> findProductDesc(String type,int start, int size,String orderColumn) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<Product> root = cq.from(Product.class);
Predicate pType=cb.equal(root.get("type"), type);
cq.where(pType);
cq.multiselect(root.get("prtdesc"));
cq.orderBy(cb.asc(root.get(orderColumn)));
TypedQuery typeQuery = entityManager.createQuery(cq);
typeQuery.setFirstResult(start);
typeQuery.setMaxResults(size);
List<String> list=typeQuery.getResultList();
return list;
}
}
更多推荐
所有评论(0)