Data返回的数据多于模型包含的数据

Data返回的数据多于模型包含的数据

本文介绍了使用Spring Data返回的数据多于模型包含的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data,这很不错,但是有时候我需要从数据库中获取更多的数据,而我的模型无法处理这些数据.例如,我的模型如下.

I'm working with Spring Data which is great stuff, but sometimes I need to get more data from database than my model can handle. For example I have model like below.

@Entity
@Table(name = "email")
public class Mail implements Serializable {

    @Getter
    @Setter
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;

    @Getter
    @Setter
    private String text;
}

我的查询会比平常更复杂.我想使用group by获取模型以及其他类似实体.

An I my query will be more complex than usual. I want to get my model and in addition number of similar entities, using group by.

@Query(value = "SELECT m, COUNT(m) as countValue FROM Mail m GROUP BY m.text")
List<Mail> findAllNewsletters();

我应该如何处理类似的事情?我的模型不包含countValue,所以我会得到List<Object[]>

How I should handle something like that? My model does't contain countValue so I will get List<Object[]>

如何处理这种情况,保持我的代码干净,容易使用这个.

How to deal with that situation, keep my code clean, easinessof using this.

推荐答案

步骤1 :创建一个容器类来保存查询的输出.

Step 1: Create a container class to hold the output from your query.

class MailOccurence {
  private final Mail mail;
  private final Long recurrence;

  public MailOccurence(final Mail mail, final Long recurrence) {
    this.mail = mail;
    this.recurrence = recurrence;
  }

  public Mail getMail() { return mail; }
  public Long getRecurrence() { return recurrence; }
}

第2步:从查询中填充并返回容器类的实例.

Step 2: Populate and return instances of the container class from the query.

Query(value = "SELECT new MailOccurence(m, COUNT(m)) FROM Mail m GROUP BY m.text")
List<MailGroup> findAllNewsletters();

有关完整的详细信息,请参见 JPA规范.

For full details, see the JPA specification.

这篇关于使用Spring Data返回的数据多于模型包含的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:24