Return more data than model contains using Spring Data

穿精又带淫゛_ 提交于 2019-12-08 20:10:46

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

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

For full details, see the JPA specification.

You can go for a DTO like following

    public class MailEntry {

    private Long id;
    private String text;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

and inside your business logic you can take the advantage of spring template something like following

@Autowired
JdbcTemplate jdbcTemplate;

private static final String SQL = "SELECT m, COUNT(m) as countValue FROM Mail m GROUP BY m.text";

public List<MailEntry> getMailEntries() {
List<MailEntry> mailEntryList = jdbcTemplate.query(SQL, new RowMapper<MailEntry>() {
        public MailEntry mapRow(ResultSet rs, int rowNum) throws SQLException {
            MailEntry mailEntry = new MailEntry();
            mailEntry.setId(rs.getInt(1));
            mailEntry.setText(rs.getString(2));
            return mailEntry;
        }
     });
     return mailEntryList;
 }

Hope this help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!