java-jpa-criteriaBuilder简介及用法

使用方法:https://blog.csdn.net/zhaoruda/article/details/80157975

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;


public class DaoImpl{

    @PersistenceContext
	protected EntityManager entityManager;

    /**
    * 查询
    * @param name 搜索条件
    */
    public Long find(String name) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root root = criteriaQuery.from(Order.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		if (StringUtils.isNotEmpty(name)) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("name"), name));
		}
		criteriaQuery.where(restrictions);
		return entityManager.createQuery(criteriaQuery).getSingleResult();
	}
}

 

你可能感兴趣的:(java)