开发者

calling genericmodel validateAndSave method won't have the record id autogenerated

I have the following code that create/save a user record, the database is the default (H2 in memory) database.

I expect that, after calling validateAndSave (of GenericModel) API on the user instance, the user will have an id autogenerated.

But I am getting a 404 at client side, ie, the code failed on 开发者_开发问答notFoundIfNull in get method.

Is that correct behavior?

public static void add(String body) {
    User user = new Gson().fromJson(body, User.class);

    if (User.findBy(user.email) != null) {
        badRequest();
    }

    user.validateAndSave();

    get(user.id);
}

public static void get(Long id) {
    User user = User.findBy(id);

    notFoundIfNull(user);

    render(user);
}


Have you checked if you are passing a null as id to get? Most likely you are, as the user you have in memory will have not been refreshed.

If you have to reuse the id try to do this:

  user = user.save();

I'm not adding validation, as right now you are not doing anything with it. ValidateAndSave (see code) returns true if the validation was ok, false otherwise. You are ignoring it, so no point on using that method.

If you still want to validate, better separate the steps: first validate and then save to obtain the new id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜