Spring Data JPA.如何从findAll()方法中获取ID列表

qzwqbdag  于 2023-10-20  发布在  Spring
关注(0)|答案(4)|浏览(155)

我有一个非常复杂的模型。实体有很多关系等等。
我尝试使用Spring Data JPA并准备了一个存储库。
但是当我调用一个方法findAll()时,指定了一个对象,这就有了一个性能问题,因为对象非常大。我知道这一点,因为当我调用这样的方法时:

@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();

我在表演上没有任何问题。
但当我调用

List<Customer> findAll();

我在表演上有很大的问题。
问题是,我需要调用findAll方法与客户规格,这就是为什么我不能使用方法返回一个数组的对象。
如何编写一个方法来查找所有具有Customer实体规范的客户,但该方法仅返回ID。
就像这样:

List<Long> findAll(Specification<Customer> spec);
  • 在这种情况下,我不能使用分页。

请帮帮我

xjreopfe

xjreopfe1#

为什么不使用@Query注解?

@Query("select p.id from #{#entityName} p")
List<Long> getAllIds();

我看到的唯一缺点是当属性id改变时,但由于这是一个非常常见的名称,不太可能改变(id =主键),这应该是可以的。

cidc1ykv

cidc1ykv2#

这现在由Spring Data使用Projections支持:

interface SparseCustomer {  

  String getId(); 

  String getName();  
}

Customer存储库中的要多

List<SparseCustomer> findAll(Specification<Customer> spec);

编辑:

正如Radouane指出的那样,由于bug的原因,ROUFID投影与规范目前不起作用。
但是你可以使用specification-with-projection库来解决这个Spring Data Jpa的缺陷。

nhn9ugyo

nhn9ugyo3#

我解决了问题。
(As结果我们将有一个稀疏的Customer对象,只有id和name)

自定义仓库:

public interface SparseCustomerRepository {
    List<Customer> findAllWithNameOnly(Specification<Customer> spec);
}

和一个实现(记住后缀- Impl是默认的)

@Service
public class SparseCustomerRepositoryImpl implements SparseCustomerRepository {
    private final EntityManager entityManager;

    @Autowired
    public SparseCustomerRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<Customer> findAllWithNameOnly(Specification<Customer> spec) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> tupleQuery = criteriaBuilder.createTupleQuery();
        Root<Customer> root = tupleQuery.from(Customer.class);
        tupleQuery.multiselect(getSelection(root, Customer_.id),
                getSelection(root, Customer_.name));
        if (spec != null) {
            tupleQuery.where(spec.toPredicate(root, tupleQuery, criteriaBuilder));
        }

        List<Tuple> CustomerNames = entityManager.createQuery(tupleQuery).getResultList();
        return createEntitiesFromTuples(CustomerNames);
    }

    private Selection<?> getSelection(Root<Customer> root,
            SingularAttribute<Customer, ?> attribute) {
        return root.get(attribute).alias(attribute.getName());
    }

    private List<Customer> createEntitiesFromTuples(List<Tuple> CustomerNames) {
        List<Customer> customers = new ArrayList<>();
        for (Tuple customer : CustomerNames) {
            Customer c = new Customer();
            c.setId(customer.get(Customer_.id.getName(), Long.class));
            c.setName(customer.get(Customer_.name.getName(), String.class));
            c.add(customer);
        }
        return customers;
    }
}
hpxqektj

hpxqektj4#

不幸的是,Projections不适用于规格。JpaSpecificationExecutor仅返回类型为存储库管理的聚合根的List(List<T> findAll(Specification<T> var1);
一个实际的解决方法是使用Tuple。范例:

@Override
    public <D> D findOne(Projections<DOMAIN> projections, Specification<DOMAIN> specification, SingleTupleMapper<D> tupleMapper) {
        Tuple tuple = this.getTupleQuery(projections, specification).getSingleResult();
        return tupleMapper.map(tuple);
    }

    @Override
    public <D extends Dto<ID>> List<D> findAll(Projections<DOMAIN> projections, Specification<DOMAIN> specification, TupleMapper<D> tupleMapper) {
        List<Tuple> tupleList = this.getTupleQuery(projections, specification).getResultList();
        return tupleMapper.map(tupleList);
    }

    private TypedQuery<Tuple> getTupleQuery(Projections<DOMAIN> projections, Specification<DOMAIN> specification) {

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> query = cb.createTupleQuery();

        Root<DOMAIN> root = query.from((Class<DOMAIN>) domainClass);

        query.multiselect(projections.project(root));
        query.where(specification.toPredicate(root, query, cb));

        return entityManager.createQuery(query);
    }

其中Projections是根投影的功能接口。

@FunctionalInterface
public interface Projections<D> {

    List<Selection<?>> project(Root<D> root);

}

SingleTupleMapperTupleMapper用于将TupleQuery结果Map到要返回的Object。

@FunctionalInterface
public interface SingleTupleMapper<D> {

    D map(Tuple tuple);
}

@FunctionalInterface
public interface TupleMapper<D> {

    List<D> map(List<Tuple> tuples);

}

用途:

Projections<User> userProjections = (root) -> Arrays.asList(
                root.get(User_.uid).alias(User_.uid.getName()),
                root.get(User_.active).alias(User_.active.getName()),
                root.get(User_.userProvider).alias(User_.userProvider.getName()),
                root.join(User_.profile).get(Profile_.firstName).alias(Profile_.firstName.getName()),
                root.join(User_.profile).get(Profile_.lastName).alias(Profile_.lastName.getName()),
                root.join(User_.profile).get(Profile_.picture).alias(Profile_.picture.getName()),
                root.join(User_.profile).get(Profile_.gender).alias(Profile_.gender.getName())
        );

        Specification<User> userSpecification = UserSpecifications.withUid(userUid);

        SingleTupleMapper<BasicUserDto> singleMapper = tuple -> {

            BasicUserDto basicUserDto = new BasicUserDto();

            basicUserDto.setUid(tuple.get(User_.uid.getName(), String.class));
            basicUserDto.setActive(tuple.get(User_.active.getName(), Boolean.class));
            basicUserDto.setUserProvider(tuple.get(User_.userProvider.getName(), UserProvider.class));
            basicUserDto.setFirstName(tuple.get(Profile_.firstName.getName(), String.class));
            basicUserDto.setLastName(tuple.get(Profile_.lastName.getName(), String.class));
            basicUserDto.setPicture(tuple.get(Profile_.picture.getName(), String.class));
            basicUserDto.setGender(tuple.get(Profile_.gender.getName(), Gender.class));

            return basicUserDto;
        };

        BasicUserDto basicUser = findOne(userProjections, userSpecification, singleMapper);

我希望能帮上忙。

相关问题