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

60

我有一个非常复杂的模型。实体之间存在很多关系等。

我尝试使用Spring Data JPA,并准备了一个存储库。

但是当我使用带有规范的方法findAll()调用对象时,会出现性能问题,因为对象非常庞大。我知道这是因为当我调用像这样的方法时:

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

我在性能方面没有任何问题。
但是当我调用时。
List<Customer> findAll(); 

我在性能方面遇到了一个大问题。
问题是,我需要使用规范来调用findAll方法以获取Customer的数据,所以我不能使用返回对象数组列表的方法。
我应该如何编写一个方法来查找所有具有Customer实体规范的客户,但只返回ID。
就像这样:
List<Long> findAll(Specification<Customer> spec);

我在这种情况下无法使用分页功能。
请帮忙。

1
这听起来正是 FetchType.LAZY 旨在解决的问题。 - Terry
1
虽然已经有所改善,但仍需要10-15秒的时间。通过使用查询查找所有结果,我可以在1-2秒内得到结果。使用Spring Data可以解决这个问题。这意味着只从特定列获取值,而不是整个对象。 - tomasz-mer
我无法想象检索整行会比单个列明显地慢。你的数据库模式让我感到恐惧!但是,我认为修复它可能是不可能的。希望有人能回答。Spring JPA非常灵活,我认为您可以使用自定义@Query轻松完成此操作。但我个人从未这样做过。 - Terry
1
看,这不是数据库的问题。 你能想象一下,例如在你的应用程序和数据库之间有一些代理时会发生什么吗? 当你想要传输一个具有两个字段的稀疏对象时和当你想要传输具有许多关系且不能使用延迟获取时的对象时,你是否看到了区别? 这就是问题所在。 - tomasz-mer
4个回答

64

为什么不使用@Query注释?

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

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


5
或者只需使用"@Query("select id from #{#entityName}")"。 (意为:或者可以仅使用"@Query("select id from #{#entityName}")"。) - Reimeus
2
它是否符合规格要求? - Emil Terman

30

现在,Spring Data 支持使用投影了:

interface SparseCustomer {  

  String getId(); 

  String getName();  
}

比在您的客户 (Customer)存储库中

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

编辑:
如Radouane ROUFID所述,由于bug的存在,目前使用带有规范的投影不起作用。

但是,您可以使用specification-with-projection库,它可以解决这个Spring Data Jpa的缺陷。


2
这对于这种用例实际上有效吗?似乎Java无法区分扩展存储库的JpaSpecificationExecutor <OriginalEntity>中的此方法和原始方法之间的区别,我不知道该给方法取什么名字。 - Markus Barthlen
1
投影不适用于规范。JpaSpecificationExecutor仅返回由存储库管理的聚合根类型的列表(List<T> findAll(Specification<T> var1);)。 - Radouane ROUFID
现在,在Spring Data 3.0.0中支持使用投影进行规范化。请参考https://github.com/spring-projects/spring-data-jpa/issues/1378#issuecomment-1103534041。 - IHaveHandedInMyResignation

12

我解决了这个问题。

(结果,我们将只有id和name两个属性的稀疏的Customer对象)

定义他们自己的存储库:

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;
    }
}

4
很不幸,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的结果映射到您想要返回的对象。

@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);

我希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接