llamar al método genericmodel validateAndSave no tendrá el ID de registro autogenerado

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);
}

preguntado el 27 de agosto de 11 a las 19:08

1 Respuestas

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 código) 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.

Respondido 30 ago 11, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.