Как заставить метод PUT работать? Я хочу обновить свои данные в таблице - PullRequest
0 голосов
/ 09 ноября 2018

Это мой метод POST, и он успешен и хорошо работает. У меня вопрос, как сделать метод запроса PUT, чтобы он мог хорошо обновлять данные?

Почтовый метод

public void addRecipe(RecipeDTO recipedto)
{
    Category categoryTitle = categoryRepository.findByCategoryTitle(recipedto.getCategoryTitle());
    Recipe recipe = new Recipe();

   /*I map my dto data original model*/

    recipe.setRID(recipedto.getrID());
    recipe.setRecipeTitle(recipedto.getRecipeTitle());
    recipe.setDescription(recipedto.getDescription());
    recipe.setCookTime(recipedto.getCookTime());

    List categoryList = new ArrayList<>();
    categoryList.add(categoryTitle);

    recipe.setCategories(categoryList);

    Recipe savedRecipe = recipeRepository.save(recipe);


    /*I map the data in ingredientDTO and setpDTO to actual model */

    List ingredientList = new ArrayList<>();
    for(IngredientDTO ingredientdto : recipedto.getIngredients())
    {   
        Ingredient ingredient = new Ingredient();

        ingredient.setIID(ingredientdto.getiID());
        ingredient.setIngredientName(ingredientdto.getIngredientName());
        ingredient.setRecipe(savedRecipe);

        ingredientList.add(ingredient);

    }

    List stepList = new ArrayList<>();
    for(StepDTO stepdto : recipedto.getSteps())
    {   
        Step step = new Step();

        step.setSID(stepdto.getsID());
        step.setStepDescription(stepdto.getStepDescription());
        step.setStepNumber(stepdto.getStepNumber());
        step.setRecipe(savedRecipe);


        stepList.add(step);

    }

    ingredientRepository.save(ingredientList);
    stepRepository.save(stepList);


}

Это мой метод пут, и он не будет работать, как я должен это делать, потому что понятия не имею. Пожалуйста, научите меня делать этот метод, если он лучше.

public void updateRecipe(RecipeDTO recipedto, String id)
{
    Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
    if(id==recipedto.getrID().toString())
    {
        recipeRepository.save(recipe);
    }
}

Ответы [ 2 ]

0 голосов
/ 09 ноября 2018

Во-первых, и очень важно, вы НЕ используете String == String для проверки равенства. Ваш код:

public void updateRecipe(RecipeDTO recipedto, String id)
{
    Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
    if(id==recipedto.getrID().toString())
    {
        recipeRepository.save(recipe);
    }
}

Должно быть:

public void updateRecipe(RecipeDTO recipedto, String id)
    {
        Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
        if(recipedto.getrID().toString().equals(id))
        {
            recipeRepository.save(recipe);
        }
    }

Почему? Поскольку равенство с == проверяет, имеют ли объекты одинаковый адрес памяти Другими словами:

new Integer(1) == new Integer(1) //false
1 == 1 //true
new String("hello") == new String("hello") //false
"hello" == "hello" //true because literal strings are stored in a String pool
new String("hello") == "hello" //false

Во-вторых, вы ДОЛЖНЫ ВСЕГДА использовать дженерики с API-интерфейсами Collection. Ваш код:

List categoryList = new ArrayList<>();

Должно быть:

List<Category> categoryList = new ArrayList<>();

И, наконец, как сказал Аскепан, вы не определили, какую платформу вы используете. В случае Джерси (реализация JAX-RS) у вас есть методы HTTP-запроса: @GET, @POST, @PUT, @DELETE, @HEAD, @ OPTIONS.

@PUT
@Produces("text/plain")
@Consumes("text/plain")
public Response putContainer() {
    System.out.println("PUT CONTAINER " + container);

    URI uri = uriInfo.getAbsolutePath();
    Container c = new Container(container, uri.toString());

    Response r;
    if (!MemoryStore.MS.hasContainer(c)) {
        r = Response.created(uri).build();
    } else {
        r = Response.noContent().build();
    }
    MemoryStore.MS.createContainer(c);
    return r;
}

Если вы используете Spring, есть @RequestMapping (method =) или короткие версии: @GetMapping, @PutMapping, @PostMapping, @ DeleteMapping.

   @GetMapping("/{id}")
    public Person getPerson(@PathVariable Long id) {
        // ...
    }

    @PutMapping
    public void add(@RequestBody Person person) {
        // ...
    }

Согласно аннотации, метод будет вызываться соответственно.

Больше информации в: Весна JAX-RS

0 голосов
/ 09 ноября 2018

При создании служб REST в Java вы обычно используете Framework, чтобы помочь вам в этом.

Как и "jax-rs": https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api/2.0 Если вы используете jax-rs, вы помечаете свой метод как метод PUT Http с аннотацией @PUT, например:

@PUT
@Path("ex/foo")
public Response somePutMethod() {
  return Response.ok().entity("Put some Foos!").build();
}

Если вы используете Spring в качестве Framework, вы помечаете свой метод PUT аннотацией @RequestMapping, например:

@RequestMapping(value = "/ex/foo", method = PUT)
public String putFoos() {
    return "Put some Foos";
}
...