jpa利用Specification实现多条件查询排序

Entity实体类:


import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import lombok.Data;

/**
 * User 
 *
 * @author [email protected]
 */
@Data
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String userId;

    private String userName;

    private String phoneNo;

    @CreationTimestamp
    @Column(insertable = false, updatable = false)
    private Instant createTime;

    @UpdateTimestamp
    @Column(insertable = false, updatable = false)
    private Instant updateTime;
}

Repository类:

import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import cn.focusmedia.kuma.allocation.entity.User;

/**
 * UserRepository
 *
 * @author [email protected]
 */
@Repository
@DynamicUpdate
public interface UserRepository extends JpaRepository, JpaSpecificationExecutor {

}

service类:

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import cn.focusmedia.kuma.allocation.entity.User;
import cn.focusmedia.kuma.allocation.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
 * UserService
 *
 * @author [email protected]
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;

    public List listUser(List userIds, String searchKeyWord) {
        return userRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List list = new ArrayList<>();
                if (!CollectionUtils.isEmpty(userIds)) {
                    list.add(root.get("userId").as(String.class).in(userIds));
                }
                if (!StringUtils.isEmpty(searchKeyWord)) {
                    list.add(criteriaBuilder.like(root.get("userName").as(String.class), "%" + searchKeyWord + "%"));
                }
                Predicate[] predicateArray = new Predicate[list.size()];
                criteriaQuery.where(criteriaBuilder.and(list.toArray(predicateArray)));
                criteriaQuery.orderBy(criteriaBuilder.asc(root.get("createTime"))); //按照createTime升序排列
                return criteriaQuery.getRestriction();
            }
        });
    }
}

测试类中使用了匿名内部类,可以lambada表达式如下:

public List listUser(List userIds, String searchKeyWord) {
        return userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(userIds)) {
                list.add(root.get("userId").as(String.class).in(userIds));
            }
            if (!StringUtils.isEmpty(searchKeyWord)) {
                list.add(criteriaBuilder.like(root.get("userName").as(String.class), "%" + searchKeyWord + "%"));
            }
            Predicate[] predicateArray = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(predicateArray)));
            criteriaQuery.orderBy(criteriaBuilder.asc(root.get("createTime"))); //按照createTime升序排列
            return criteriaQuery.getRestriction();
        });
    }


 

你可能感兴趣的:(java,数据库)