javax.ws.rs.core.Response构建无法保留对象的信息

时间:2017-05-29 04:11:24

标签: java spring hibernate spring-mvc spring-boot

我正在尝试实施休息通话。前端得到:

[{},{}]

资源代码:

@Component
@Path(ResourcePaths.ROOT_PATH)
public class VideoResource {

    @Autowired
    private ReadVideoService readVideoService;

    @GET
    @Path(ResourcePaths.POPULAR)
    @Produces({MediaType.APPLICATION_JSON})
    public Response getVideo() {

        ResponseBuilder responseBuilder = Response.status(Response.Status.OK);
        List<Video> videos = readVideoService.getAllVideos();

        //GenericEntity<List<Video>> entity = new GenericEntity<List<Video>>(videos);

        //here it is able to print class info(from class member value)
        System.out.println(videos.get(0).toString() +" "+ videos.get(1).toString());

        return responseBuilder.entity(videos).build();
    }

}

但下面的行能够打印从服务层返回的对象的信息。

System.out.println(videos.get(0).toString() +" "+ videos.get(1).toString());

所以我猜问题出在这一行:

return responseBuilder.entity(videos).build();

我还尝试使用 GenericEntity

GenericEntity<List<Video>> entity = new GenericEntity<List<Video>>(videos);

但是它会导致以下错误,我不明白 java.lang.reflect.Type 指的是什么:

Error:(37, 45) java: constructor GenericEntity in class javax.ws.rs.core.GenericEntity<T> cannot be applied to given types;
  required: java.util.List<com.mondo.mondo_service.rest.model.Video>,java.lang.reflect.Type
  found: java.util.List<com.mondo.mondo_service.rest.model.Video>
  reason: actual and formal argument lists differ in length

这是服务层:

@Component
public class ReadVideoService {

    @Autowired
    public VideoDao videoDao;
    public List<Video> getAllVideos() {
        return videoDao.findAll();
    }

}

这是dao对象:

@Repository
public class VideoDao extends BaseDao<Video> {

    public List<Video> findAll() {
        Session database = sessionFactory.openSession();

        Query taskQuery = database.createQuery("select v from Video v");
        List<Video> videos = taskQuery.list();

        database.close();
        return videos;
    }

}

实体对象:

@Entity
@Table(name = "md_video")
public class Video implements Serializable{

    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id")
    private int id;
    private String title;
    private String url;
    private int duration;
    private String img;
    private String source;

    @Override
    public String toString() {
        return title;
    }
}

--------------更新---------------

我试图将下面的行分解为三行:

return responseBuilder.entity(videos).build();

responseBuilder = responseBuilder.entity(videos);
Response res = responseBuilder.build();
return res;

奇怪的是,我在第二种情况下发现它到达返回res; 响应对象 res 仍然包含所有实体信息。那么为什么返回后信息会丢失?

enter image description here

1 个答案:

答案 0 :(得分:0)

发现问题,我的实体对象中没有getter和setter。添加getter和setter后,实体信息会正确返回。