我只想对某些类型的用户实施分页。表结构为:

@Entity
@Table(name = "users")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, updatable = false, nullable = false, length = 3)
    private int id;

    @Column(length = 255)
    private String login;

    @Column(length = 255)
    private String email;

    @Column(length = 64)
    private String salt;

    @Column(length = 255)
    private String type;
    .....
}


仓库:

@Repository
public interface UserRepository extends JpaRepository<Users, Integer> {

}


查询:

@Override
public Page<Users> findAll(int page, int size) {
    return dao.findAll(PageRequest.of(page, size));
}


如何限制查询仅选择type admin,super_admin等。

我想我需要添加像IN(adminsuper_admin)这样的限制吗?

最佳答案

可能最简单的方法是使用命名约定并使用findAllByTypeIn

interface UserRepository extends JpaRepository<User, Integer> {
  Page<User> findAllByTypeIn(Pageable page,String... types));
}


但是,如果您有更复杂的搜索条件,我会考虑使用规范

Spring Data JPA支持规范,您可以使用JpaSpecificationExecutor接口扩展存储库接口,如下所示:

interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {

}


写下您的规格

class UserSpecs {

    public static Specification<User> isOfType(String type) {

        return new Specification<User>() {

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                return builder.equal(root.get("type"), type);
            }
        };
    }


    public static Specification<User> isInTypes(String... types) {

        return new Specification<User>() {

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
               In<String> inClause = builder.in(root.get("type"));
               for (String type: types) {
                 inClause.value(type);
               }
               return inClause;
            }
        };
    }

}


并通过获得结果

dao.findAll(UserSpecs.isOfType("admin").or(UserSpecs.isOfType("super_admin")) ,PageRequest.of(page, size));


或者如果您更喜欢在

dao.findAll(UserSpecs.isInTypes("admin","super_admin")) ,PageRequest.of(page, size));

08-17 18:12