Z
Z
zawarnoy2018-04-29 17:03:00
Java
zawarnoy, 2018-04-29 17:03:00

Spring, CrudRepository, how to implement update action?

Entities are not updated using the repository.save() method, here is my update method:

@Transactional
    @RequestMapping(method = RequestMethod.PUT, path = "/{id}")
    public @ResponseBody
    String update(@PathVariable(value = "id") String id,
                            @RequestParam(required = false) String login,
                            @RequestParam(required = false) String name,
                            @RequestParam(required = false) String password) {
        Optional<User> user = userRepository.findById(Long.valueOf(id));

        if (user.isPresent()){

            User u = user.get();

            if (login != null)
                u.setLogin(login);

            if (name != null)
                u.setUsername(name);

            if (password != null)
                u.setPassword(password);

            userRepository.save(u);
            return "{ status : success }";
        }

        return "{ status : error }";
    }

And the repository:
package spp.lab.reposository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import spp.lab.models.User;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

}

Perhaps someone faced a similar problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
idyoshin, 2018-05-03
@idyoshin

It's simple - forget to "wash away" the changes. After `userRepository.save(u);` execute `userRepository.flush();` or in one hop `userRepository.saveAndFlush(u);`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question