How do I update an entity using spring-data-jpa?

后端 未结 10 1816
眼角桃花
眼角桃花 2020-11-29 15:12

Well the question pretty much says everything. Using JPARepository how do I update an entity?

JPARepository has only a save method, which does not t

10条回答
  •  情歌与酒
    2020-11-29 15:43

    Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.

    For this particular purpose one can introduce a composite key like this:

    CREATE TABLE IF NOT EXISTS `test`.`user` (
      `username` VARCHAR(45) NOT NULL,
      `firstname` VARCHAR(45) NOT NULL,
      `description` VARCHAR(45) NOT NULL,
      PRIMARY KEY (`username`, `firstname`))
    

    Mapping:

    @Embeddable
    public class UserKey implements Serializable {
        protected String username;
        protected String firstname;
    
        public UserKey() {}
    
        public UserKey(String username, String firstname) {
            this.username = username;
            this.firstname = firstname;
        }
        // equals, hashCode
    }
    

    Here is how to use it:

    @Entity
    public class UserEntity implements Serializable {
        @EmbeddedId
        private UserKey primaryKey;
    
        private String description;
    
        //...
    }
    

    JpaRepository would look like this:

    public interface UserEntityRepository extends JpaRepository
    

    Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.

提交回复
热议问题