如何使用JPA本机查询将List <object>转换为POJO

时间:2019-04-16 15:04:10

标签: java spring jpa

如何将对象列表转换为josn(键,值)格式?

我正在上一个名为ClientRT的课程,在该课程中有四个字段,即

res_nclient_room_type_id, res_sclient_rt_desc,res_sclient_rt_name, res_sclient_rt_code

服务等级

public List<Object> callSP() throws IOException {   

        List<Object> crt=crtRepo.roomtype(60);          

        //ObjectMapper mapper = new ObjectMapper(); 

        //String rtobject= mapper.writeValueAsString(crt);

        return crt;
    }

存储库

@Repository
public interface ClientRoomTypeRepository extends JpaRepository<ClientRoomType, Integer> {

    @Query(value = "select * from roomtype(:int_inst_id)", nativeQuery = true)
    List<Object> roomtype(@Param("int_inst_id")Integer int_inst_id);
}

对象列表

 [
      [
        1,
        "TEMPORARILY NOT ASSIGNED",
        "TEMPORARILY NOT ASSIGNED",
        "000"
      ],
      [
        2,
        "FACILITIES - AVAILABLE ROOM",
        "FACILITIES - AVAILABLE ROOM",
        "050"
      ],

如何以这种格式转换

[
 {
    "res_nclient_room_type_id":1 , 
    "res_sclient_rt_desc": "TEMPORARILY NOT ASSIGNED", 
    "res_sclient_rt_name":"TEMPORARILY NOT ASSIGNED" , 
    "res_sclient_rt_code":"000" 

 },
 {
  "res_nclient_room_type_id":2 , 
  "res_sclient_rt_desc": "FACILITIES - AVAILABLE ROOM", 
  "res_sclient_rt_name":"FACILITIES - AVAILABLE ROOM" , 
  "res_sclient_rt_code":"050" 
 },
]

有人可以建议我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

我看到您的问题是JPA使用投影来做到这一点,并创建一个包含字段Interface-based Projections 的界面

interface ClientRT {

  Long getResNclientRoomTypeId();
  String getResSclientRtDesc();
  String getResSclientRtName();
  String getResSclientRtCode();
  }

查询

 @Query(value = "select * from roomtype(:int_inst_id)", nativeQuery = true)
List<ClientRT> roomtype(@Param("int_inst_id")Integer int_inst_id);