-
使用数组接收:您可以使用
Object[]
类型的数组来接收查询结果中的每一行数据。在这种情况下,数组的每个元素将包含查询结果中的一个列的值。例如:@Repository public interface HazardApplicationRepository extends JpaRepository<HazardApplication, Long> { @Query(value = "SELECT t.type, count(*) FROM tb_hazard_application t WHERE t.deleted = false GROUP BY t.type ORDER BY t.type ASC", nativeQuery = true) List<Object[]> countByType(); }
然后,您可以在代码中使用索引来访问每个数组元素的值,如下所示:
List<Object[]> result = hazardApplicationRepository.countByType(); for (Object[] row : result) { String type = (String) row[0]; Long count = (Long) row[1]; // do something with type and count }
2.使用 DTO 对象接收:您可以定义一个 Java 类来表示查询结果中的每一行数据,并使用该类的实例来接收查询结果。在这种情况下,DTO 类的属性名称应与查询结果中的列名相匹配。例如:
public class CountByTypeResult { private String type; private Long count; // getters and setters } @Repository public interface HazardApplicationRepository extends JpaRepository<HazardApplication, Long> { @Query(value = "SELECT t.type, count(*) FROM tb_hazard_application t WHERE t.deleted = false GROUP BY t.type ORDER BY t.type ASC", nativeQuery = true) List<CountByTypeResult> countByType(); }
然后,您可以在代码中使用 DTO 对象的属性来访问查询结果中的每个列的值,如下所示:
List<CountByTypeResult> result = hazardApplicationRepository.countByType(); for (CountByTypeResult row : result) { String type = row.getType(); Long count = row.getCount(); // do something with type and count }
3.使用List<Map<String, Object>>对象接收:这种接收方式可以把数据库中的字段及结果都查询出来
@Repository public interface HazardApplicationRepository extends JpaRepository<HazardApplication, Long> { @Query(value = "SELECT t.type, count(*) FROM tb_hazard_application t WHERE t.deleted = false GROUP BY t.type ORDER BY t.type ASC", nativeQuery = true) List<Map<String, Object>> countByType(); }
在这个示例中,我们更新了
countByType()
方法的返回类型,以便返回一个List<Map<String, Object>>
对象。在查询结果中,每一行的数据将被映射到一个Map<String, Object>
对象中,并添加到返回的列表中。然后,您可以在代码中使用键来访问每个映射条目的值,如下所示:
List<Map<String, Object>> result = hazardApplicationRepository.countByType(); for (Map<String, Object> row : result) { String type = (String) row.get("type"); Long count = (Long) row.get("count(*)"); // do something with type and count }
4.使用JSONObject对象接收:这种接收方式可以把数据库中的字段及结果都查询出来
@Repository public interface HazardApplicationRepository extends JpaRepository<HazardApplication, Long> { @Query(value = "SELECT t.type, count(*) FROM tb_hazard_application t WHERE t.deleted = false GROUP BY t.type ORDER BY t.type ASC", nativeQuery = true) List<JSONObject> countByType(); }
在这个示例中,我们更新了
countByType()
方法的返回类型,以便返回一个List<JSONObject>
对象。在查询结果中,每一行的数据将被映射到一个List<JSONObject>
对象中,并添加到返回的列表中。然后,您可以在代码中使用键来访问每个映射条目的值,如下所示:
List<JSONObject> result = hazardApplicationRepository.countByType(); for (JSONObject row : result) { String type = (String) row.get("type"); Long count = (Long) row.get("count(*)"); // do something with type and count }
Mysql查询结果对应的java参数接收
最新推荐文章于 2023-10-13 10:28:05 发布