我有更新方法来更新电影.但是当我在邮递员中提供数据时,我输入一个字段,然后保留字段获得空值



这是电影列表。

public static List<Movie> movies;
static {
movies = new ArrayList<>();
movies.add(new Movie(1, "Fprd vs Ferrari", "Movie on Racing", "abcd", "xyz"));
movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
}

这是更新方法:

public Result update(Http.Request request, int id) {
Movie movie = findById(id);
if (movie == null) {
return notFound("Movie not Found");
}
JsonNode jsonNode = request.body().asJson();
Movie movie1 = Json.fromJson(jsonNode, Movie.class);
movie1.setId(id);
int index = movies.indexOf(movie);
movies.set(index, movie1);
return ok(Json.toJson(movie1));
}

当我使用邮递员发送数据时,例如我只会给出电影名称,然后电影将更新,但其余字段将获得空值。

但是我想更新数据,如果我没有发送任何字段,它将与对象的现有值一起存储。

我该怎么做..那是什么条件

提醒一下:在 RESTful 设计中,有两种类似的方法:PUT,它使用您正在传递的值(包括空值,就像您当前的实现一样(更新您的实体,以及PATCH,仅更新非值字段。

[更好的解释:https://medium.com/backticks-tildes/restful-api-design-put-vs-patch-4a061aa3ed0b]

所以我的方法是实现两个变体:

public Result put(Http.Request request, int id) {
return update(request,id,true);
}
public Result patch(Http.Request request, int id) {
return update(request,id,false);
}
private Result update(Http.Request request, int id, boolean forceUpdate) {
Movie existing = findById(id);
if (existing == null) {
return notFound("Movie not Found");
}
JsonNode jsonNode = request.body().asJson();
Movie received = Json.fromJson(jsonNode, Movie.class);
if (forceUpdate || received.getMovieName() != null) {
existing.setMovieName(received.getMovieName());
}
// same for the rest of fields in Movie. You may want to use reflection
// instead of writing the same for each field manually
...
return ok(Json.toJson(existing));
}

实际上,您的请求包含唯一的电影名称。而且您不会使用电影对象更新该名称。您必须将movie1的所有值更新为电影对象,然后它将获得这样的更新。

public Result update(Http.Request request, int id) {
Movie movie = findById(id);
if (movie == null) {
return notFound("Movie not Found");
}
JsonNode jsonNode = request.body().asJson();
Movie movie1 = Json.fromJson(jsonNode, Movie.class);
movie.setMovieName(movie1.getMovieName()); 
int index = movies.indexOf(movie);
movies.set(index, movie);
return ok(Json.toJson(movie));
}

最新更新