gpt4 book ai didi

java - 在Spring Boot中的JPA查询中使用规范

转载 作者:行者123 更新时间:2023-12-01 18:26:35 24 4
gpt4 key购买 nike

我有一个表名high_utilization,

与列,

varchar name_utilization, 
float utilization,
varchar monitoring_tool,
varchar location,
varchar device_type,
varchar environment,
varchar Org_filter_1,
varchar Org_filter_2,
varchar Domain_filter_1,
varchar Domain_filter_2;


但是在以JSON格式输出时,我只需要两个字段 name_utilization, utilization

我正在写下我的存储库文件,如下所示

public interface high_utilizationRepo extends CrudRepository<high_utilization,Integer> {
@Query(value="select a.name_utilization as 'name_utilization',a.utilization as 'utilization' "
+ " from high_utilization a WHERE a.monitoring_tool in (:monitoring_tool) "
+ "AND a.location in (:location) AND a.device_type in (:device_type) AND a.environment in (:environment) "
+ "AND a.Org_filter_1 in (:Org_filter_1) AND a.Org_filter_2 in (:Org_filter_2) AND "
+ "a.Domain_filter_1 in (:Domain_filter_1) AND a.Domain_filter_2 in (:Domain_filter_2) "
+ " order by utilization desc limit 5",nativeQuery=true)
String[] info_of_high_utilization_with_params(@Param("monitoring_tool") List<String>
monitoring_tool,
@Param("location") List<String> location, @Param("device_type") List<String> device_type,
@Param("environment") List<String> environment,@Param("Org_filter_1") List<String> Org_filter_1,
@Param("Org_filter_2") List<String> Org_filter_2,@Param("Domain_filter_1") List<String> Domain_filter_1,
@Param("Domain_filter_2") List<String> Domain_filter_2);


我知道我可以使用 findAll(Specification <high_utilization>)
但我想在自己定义的具有8个参数的函数info_of_high_utilization_with__params上使用该规范。

我应该如何写下程序?

最佳答案

如您所见,当您执行自定义查询时,它返回对象数组(这里是字符串)。因此,您必须根据需要手动设置。


通常,我们根据用户要求使用DTO处理json请求。因此,我建议您使用以下方式。


例:

DTO:

@Data
public class TempDTO {
private String email;
private String phno;
}


仓库:

@Query(nativeQuery = true, value = "SELECT email, phone_no FROM ec_user")
List<String[]> findEmailAndPhoneNoBasedOnUsername();


服务:

  @Override
public List<TempDTO> getEmailAndPhoneNo(String username) {
List<TempDTO> result = new ArrayList<>();
List<String[]> dataList = userRepository.findEmailAndPhoneNoBasedOnUsername();
for (String[] strArray : dataList) {
TempDTO tempDTO = new TempDTO();
tempDTO.setEmail(strArray[0]);
tempDTO.setPhno(strArray[1]);
result.add(tempDTO);
}
return result;
}


使用流api进行服务。

关于java - 在Spring Boot中的JPA查询中使用规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60219744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com