Spring Data JPA: How to update a model elegantly?

后端 未结 2 2039
醉梦人生
醉梦人生 2020-12-16 02:30
  1. My Model is like this:

    @Entity
    @Table(name = \"user\")
    public class User {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private          
    
    
            
相关标签:
2条回答
  • 2020-12-16 02:38

    At first I need to say the Patch solution by @Oliver Gierke is really great.

    And In my previous project, my solution is:
    1. Create a abstract class to implement JpaRepository, and implement save() function.
    2. In the save function, get the entity from DB. It not exist, just save it. Otherwise, use reflection to get all NOT NULL fields from the updated entity, and set into entity from DB. (it is similar as you do, but I did it for all save function)

    0 讨论(0)
  • 2020-12-16 02:39

    The easiest way is an appropriately set up controller method:

    @RequestMapping(value = "/users/{user}", method = RequestMethod.PATCH)
    public … updateUser(@ModelAttribute User user) { … }
    

    According to the reference documentation when this method is called the following steps happen:

    1. An instance of User needs to be obtained. This basically requires a Converter from String to User to be registered with Spring MVC to convert the path segment extracted from the URI template into a User. If you're e.g. using Spring Data and enable its web support as described in its reference documentation, this will work out of the box.
    2. After the existing instance was obtained, request data will be bound to the existing object.
    3. The bound object will be handed into the method.

    Additional hints

    • Don't use GET as HTTP method for updates. GET is defined to be a safe operation (no side effects), which an update is not. PATCH is the correct method here as it's defined to allow partial updates to an existing resource.
    • To submit form data into PUT and PATCH requests, you need to register an HttpPutFormContentFilter with the application as described here. I filed an issue with Spring Boot to register that by default.
    0 讨论(0)
提交回复
热议问题