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

后端 未结 10 1353
眼角桃花
眼角桃花 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

    Using spring-data-jpa save(), I was having same problem as @DtechNet. I mean every save() was creating new object instead of update. To solve this I had to add version field to entity and related table.

    0 讨论(0)
  • 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<UserEntity, UserKey>
    

    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.

    0 讨论(0)
  • 2020-11-29 15:45

    If your primary key is autoincrement then, you have to set the value for the primary key. for the save(); method to work as a update().else it will create a new record in db.

    if you are using jsp form then use hidden filed to set primary key.

    Jsp:

    <form:input type="hidden" path="id" value="${user.id}"/>

    Java:

    @PostMapping("/update")
    public String updateUser(@ModelAttribute User user) {
        repo.save(user);
        return "redirect:userlist";
    }
    

    also look at this:

    @Override
      @Transactional
      public Customer save(Customer customer) {
    
        // Is new?
        if (customer.getId() == null) {
          em.persist(customer);
          return customer;
        } else {
          return em.merge(customer);
        }
      }
    
    0 讨论(0)
  • 2020-11-29 15:53

    Since the answer by @axtavt focuses on JPA not spring-data-jpa

    To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER

    Spring-data-jpa supports update operation.
    You have to define the method in Repository interface.and annotated it with @Query and @Modifying.

    @Modifying
    @Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
    void setUserInfoById(String firstname, String lastname, Integer userId);
    

    @Query is for defining custom query and @Modifying is for telling spring-data-jpa that this query is an update operation and it requires executeUpdate() not executeQuery().

    You can specify other return types:
    int - the number of records being updated.
    boolean - true if there is a record being updated. Otherwise, false.


    Note: Run this code in a Transaction.

    0 讨论(0)
提交回复
热议问题