Jpa Specification 实现 and和or 同时使用查询

同时使用and和or的查询

UserServiceImpl 类,service实现类

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private RongUserRepository rongUserRepository;


     //FriendNumResult  自定的返回类型
    //FriendNumParam  自定义的封装参数的类型
    //RongUser  实体类型
    @Override
    public FriendNumResult friendNum(FriendNumParam friendNumParam) {
        FriendNumResult friendNumResult=new FriendNumResult();

        Specification specification = new Specification(){

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //封装and语句
                List listAnd = new ArrayList();
                //这里是hql,所以root.get(),方法里面必须是对应的实体属性
                listAnd.add(criteriaBuilder.equal(root.get("perLevel").as(Integer.class), friendNumParam.getPerLevel()));
                Predicate[] array_and=new Predicate[listAnd.size()];
                Predicate Pre_And = criteriaBuilder.and(listAnd.toArray(array_and));

                //封装or语句
                List listOr = new ArrayList();
                listOr.add(criteriaBuilder.equal(root.get("fId").as(Integer.class), friendNumParam.getUid()));
                listOr.add(criteriaBuilder.equal(root.get("fId2").as(Integer.class), friendNumParam.getUid()));
                Predicate[] arrayOr = new Predicate[listOr.size()];
                Predicate Pre_Or = criteriaBuilder.or(listOr.toArray(arrayOr));

                return criteriaQuery.where(Pre_And,Pre_Or).getRestriction();
                //单独使用  and 或者  or 时 返回
                //return criteriaBuilder.and(list.toArray());
            }
        };
        long num=this.rongUserRepository.count(specification);
        friendNumResult.setFriendNum(Integer.valueOf((int)num));
        return friendNumResult;
    }
}
RongUserRepository接口
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;


//RongUser  自己的实体类型
public interface RongUserRepository extends JpaRepository , JpaSpecificationExecutor {
}

 

注意:使用Specification之前,RongUserRepository接口必须实现JpaSpecificationExecutor,RongUser对应表的实体类

 

你可能感兴趣的:(Jpa Specification 实现 and和or 同时使用查询)