如何使用Spring Boot从自定义查询中返回带有几个字段的自定义列表?

时间:2019-06-23 11:20:30

标签: java spring-boot

我正在使用Spring Boot 2和Java 8开发REST Web服务。与获取包含表中所有字段的列表相比,我在创建具有很少字段的列表时遇到了问题。

@Query("SELECT c.idCliente, c.nome, c.cognome, c.username, c.email FROM Cliente c WHERE c.username LIKE %:username%")
List<Cliente> findClienteByUsername(@Param("username") String username);

结果是:

[
   3,
   null,
   null,
   "user",
   "aaa"
]

但是,当显示所有字段时,请执行以下操作:

{"idCliente":3,"username":"user","nome":null,"cognome":null,"dataNascita":null,"email":"aaa","password":"ciao","dataCreazione":"2018-11-23T21:33:31.000+0000","instagram":null,"facebook":null,"google":null,"twitter":null,"attivo":"1","ultimaSospensione":null}

为什么不能同时获取字段名称和值?

2 个答案:

答案 0 :(得分:3)

尽管您必须通过DTO类选择一些与Spring Projection一起使用的字段。您必须使用所选字段定义构造函数。

@Query("SELECT new Cliente(c.idCliente, c.nome, c.cognome, c.username, c.email) FROM Cliente c WHERE c.username LIKE %:username%")
List<Cliente> findClienteByUsername(@Param("username") String username);

您可以在下面的链接中找到详细信息。 https://smarterco.de/spring-data-jpa-query-result-to-dto/

或者您可以使用映射器功能对每一行进行手动翻译。

 @Query("SELECT c.id, c.nome, c.cognome, c.username, c.email FROM Cliente c WHERE c.username LIKE %:username%")
List<Object[]> findClientDeatailsByuserName(@Param("username")String username);

答案 1 :(得分:0)

尝试以下方法:在Cliente实体类中创建下面提到的构造函数。

Cliente(int idCliente,String noame,String cognome,String username,String email){
   this.idCliente=idCliente;
   this.nome=nome;
   this.cognome=cognome;
   this.username=username;
   this.email=email;   
 }

以以下方式调用查询:

@Query("SELECT new packageName.Cliente(c.idCliente, c.nome, c.cognome, c.username, c.email) FROM Cliente c WHERE c.username LIKE %:username%")
List<Cliente> findClienteByUsername(@Param("username") String username);

它将显示所有带有值的字段。