我有一个非常复杂的模型。实体有很多关系,等等。
我尝试使用Spring Data JPA并准备了一个存储库。
但是当我调用带有对象规范的metod findAll()时会出现性能问题,因为对象非常大。我知道,因为当我调用这样的方法时:
@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();
我的表现没有任何问题。
但是当我调用
时List<Customer> findAll();
我的表现存在很大问题。
问题是我需要使用规范客户调用findAll方法,这就是为什么我不能使用返回对象数组列表的方法。
如何编写方法来查找具有Customer实体规范但仅返回ID的所有客户。
像这样:List<Long> findAll(Specification<Customer> spec);
请帮忙。
答案 0 :(得分:25)
为什么不使用@Query
注释?
@Query("select p.id from #{#entityName} p")
List<Long> getAllIds();
我看到的唯一缺点是属性id
发生了变化,但由于这是一个非常常见的名称而且不太可能改变(id =主键),这应该没问题。
答案 1 :(得分:17)
Spring Data使用Projections:
支持此功能interface SparseCustomer {
String getId();
String getName();
}
比在Customer
存储库中
List<SparseCustomer> findAll(Specification<Customer> spec);
修改强>
正如Radouane ROUFID预测的那样,规范目前并不适用于bug。
但是你可以使用specification-with-projection库来解决这个Spring Data Jpa缺陷。
答案 2 :(得分:8)
我解决了这个问题。
(因此我们将只有一个带有id和名称的稀疏Customer对象)
public interface SparseCustomerRepository {
List<Customer> findAllWithNameOnly(Specification<Customer> spec);
}
@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;
}
}
答案 3 :(得分:0)
不幸的是Projections不适用于specifications。 JpaSpecificationExecutor
仅返回使用存储库管理的聚合根键入的列表(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);
}
SingleTupleMapper
和TupleMapper
用于将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);
我希望它有所帮助。
答案 4 :(得分:-1)
您可以使用流获取客户服务类中的所有 ID。
public List<String> listIds() {
return customerRepository.findAll().stream()
.map(customer -> customer.getId())
.collect(Collectors.toList());
}