spring-data specifications - return list of ids in

2020-07-18 07:57发布

问题:

i'm looking to get all ids of all subscribed users. this is my predicate:

public static Specification<User> userSubscribed(){
  return new Specification<User>() {
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
      return builder.equal(root.get("status"), 1 /* 1 = subscribed */);
    }
  };
}

My repository, however, only allows count, findAll and findOne. Is there a way to get it to return a list of a certain field?

回答1:

As far as I know this isn't supported by Spring-Data yet. Read a response from Oliver Gierke on related question. And those issues that were mentioned there are still open.

As an alternative you can create a custom repository and use TypedQuery to achive what you want. Here are some examples of TypedQuery: http://www.objectdb.com/java/jpa/query/jpql/select

Example of TypedQuery:

TypedQuery<Integer> query = em.createQuery(
    "SELECT u.id FROM User AS u", Integer.class);
// ... Some predicates
List<Integer> results = query.getResultList();


标签: spring-data