实现一个返回数组的接口

Rest层

先找对要查询什么表先,然后在那个表对应的rest层增加新的接口

  @ApiOperation(value = "获取实例包主键数组")
  @GetMapping(value = "/instanceId/{id}")
  public ResponsePacket<> get(@PathVariable(value = "id") String packetSubTaskId) {

  }

Service层

因为要实现用一个id查询多条id数据,返回有可能是一条、多条甚至是没有,所以用一个List数组作为返回值。

  public List<String> getInstancePacketIds(String packetSubTaskId) {
    List<String> instancePacketIds = mapper.getInstancePacketIds(packetSubTaskId);
    return instancePacketIds;
  }

Mapper层

在interface增加:

public interface TFlowPacketSubTaskRelMapper {
      List<String> getInstancePacketIds(String packetSubTaskId);
}

然后是xml文件

  <select id="getInstancePacketIds" resultType="String">
    select packet_instance_id
    from
    <include refid="table_name"/>
    where
    packet_sub_task_id = #{packetSubTaskId}
  </select>

很简单的一条sql,其实就是

select packet_instance_id
from t_flow_packet_sub_task_rel
where packet_sub_task_id = #{packetSubTaskId}

然后就完成了,可以回去写rest了。

完善Rest层:实现数组返回

现在回来完善rest层,因为ResponsePacket没有List这样的参数可以传,所以要自己写一个DTO来把List包起来,里边有List的get和set方法:

  private final class ResponseDTO<T> extends BaseResponseData {

    private List<T> data;

    public void setData(List<T> data) {
      this.data = data;
    }

    public List<T> getData() {
      return data;
    }
  }

然后把传来的List数组放入DTO里,再把DTO放进ResponsePacket里:

  @ApiOperation(value = "获取实例包主键数组")
  @GetMapping(value = "/instanceId/{id}")
  public ResponsePacket<ResponseDTO<String>> get(@PathVariable(value = "id") String packetSubTaskId) {
    List<String> instancePacketIds = service.getInstancePacketIds(packetSubTaskId);
    ResponseDTO<String> responseDTO = new ResponseDTO<>();
    responseDTO.setData(instancePacketIds);
    ResponsePacket<ResponseDTO<String>> responsePacket = new ResponsePacket<ResponseDTO<String>>();
    responsePacket.setCode(ResponseStatus.OK.getCode());
    responsePacket.setMsg(ResponseStatus.OK.getMsg());
    responsePacket.setData(responseDTO);
    return responsePacket;
  }

  private final class ResponseDTO<T> extends BaseResponseData {

    private List<T> data;

    public void setData(List<T> data) {
      this.data = data;
    }

    public List<T> getData() {
      return data;
    }
  }

就这样实现了接口。


   转载规则


《实现一个返回数组的接口》 锦泉 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录