Spring Data JPA.如何仅从findAll()方法获取ID列表 [英] Spring Data JPA. How to get only a list of IDs from findAll() method
问题描述
我有一个非常复杂的模型.实体有很多关系,依此类推.
I have a very complicated model. Entity has a lot relationship and so on.
我尝试使用Spring Data JPA,并准备了一个存储库.
I try to use Spring Data JPA and I prepared a repository.
但是当我用对象的规范调用方法findAll()时,会出现性能问题,因为对象很大.我知道这是因为当我调用这样的方法时:
but when I invoke a method findAll() with specification for the object a have a performance issue because objects are very big. I know that because when I invoke a method like this:
@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();
我的表现没有任何问题.
I didn't have any problems with performance.
但是当我调用
List<Customer> findAll();
我对性能有很大的疑问.
I had a big problem with performance.
问题是我需要使用客户规格"来调用findAll方法,这就是为什么我不能使用返回对象数组列表的方法的原因.
The problem is that I need to invoke findAll method with Specifications for Customer that is why I cannot use method which returns a list of arrays of objects.
如何编写一种方法来查找所有具有客户实体规范但仅返回ID的客户.
How to write a method to finding all customers with specifications for Customer entity but which returns only an IDs.
像这样:
List<Long> findAll(Specification<Customer> spec);
- 在这种情况下,我无法使用分页.
请帮助.
推荐答案
我解决了这个问题.
(因此,我们将只有ID和名称为稀疏的Customer对象)
(As a result we will have a sparse Customer object only with id and 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;
}
}
这篇关于Spring Data JPA.如何仅从findAll()方法获取ID列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!