Spring Data JPA:与Pageable一起使用,但与实体的一组特定字段一起使用 [英] Spring Data JPA: Work with Pageable but with a specific set of fields of the entity

查看:456
本文介绍了Spring Data JPA:与Pageable一起使用,但与实体的一组特定字段一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data 2.0.6.RELEASE.

出于性能和演示目的,我正在研究分页. 在这里,关于性能,我说的是,如果我们有很多记录,最好将它们显示在页面上

我满足以下条件并且工作正常:

interface PersonaDataJpaCrudRepository extends PagingAndSortingRepository<Persona, String> {
}

@Controller适用于:

@GetMapping(produces=MediaType.TEXT_HTML_VALUE)
public String findAll(Pageable pageable, Model model){

通过Thymeleaf我可以应用分页.因此,到这里为止,目标已经实现.

注意:Persona类用JPA注释(@EntityId等)

现在,我担心以下问题:即使分页在Spring Data中起作用,但有关记录的数量,每条记录的内容又如何呢?

我的意思是:假设Persona类包含20个字段(考虑您想要为您的应用创建的任何实体),因此对于基于html的视图,其中 report 仅使用4个字段(id,名字,姓氏,日期),因此对于内存中的每个实体,我们有16个不必要的字段

我尝试了以下操作:

interface PersonaDataJpaCrudRepository extends PagingAndSortingRepository<Persona, String> {

    @Query("SELECT p.id, id.nombre, id.apellido, id.fecha FROM Persona p")
    @Override
    Page<Persona> findAll(Pageable pageable);

}

如果我在@Controller中进行简单打印,则以下内容将失败:

java.lang.ClassCastException: 
[Ljava.lang.Object; cannot be cast to com.manuel.jordan.domain.Persona

如果我避免视图失败,请执行以下操作:

Caused by: 
org.springframework.expression.spel.SpelEvaluationException: 
EL1008E: 
Property or field 'id' cannot be found on object of type 
'java.lang.Object[]' - maybe not public or not valid?

我已经阅读了很多SO的帖子,例如:

我理解答案,并且我同意Object[]返回类型,因为我正在处理特定的字段集.

  1. 是否必须对每个实体使用完整的字段集?在这种情况下,我是否应该简单地接受大约16个字段的内存开销,而这些开销却从未使用过?是否为每个检索到的记录?
  2. 是否有解决方案来处理一组特定字段或使用当前API Spring DataObject[]?

解决方案

看看Spring数据

If I do a simple print in the @Controller it fails about the following:

java.lang.ClassCastException: 
[Ljava.lang.Object; cannot be cast to com.manuel.jordan.domain.Persona

If I avoid that the view fails with:

Caused by: 
org.springframework.expression.spel.SpelEvaluationException: 
EL1008E: 
Property or field 'id' cannot be found on object of type 
'java.lang.Object[]' - maybe not public or not valid?

I have read many posts in SO such as:

I understand the answer and I am agree about the Object[] return type because I am working with specific set of fields.

  1. Is mandatory work with the complete set of fields for each entity? Should I simply accept the cost of memory about the 16 fields in this case that never are used? It for each record retrieved?
  2. Is there a solution to work around with a specific set of fields or Object[] with the current API of Spring Data?

解决方案

Have a look at Spring data Projections. For example, interface-based projections may be used to expose certain attributes through specific getter methods.

Interface:

interface PersonaSubset {
    long getId();
    String getNombre();
    String getApellido();
    String getFecha();
}

Repository method:

Page<PersonaSubset> findAll(Pageable pageable);

这篇关于Spring Data JPA:与Pageable一起使用,但与实体的一组特定字段一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆