Update an entity using spring data JPA

来源:互联网 发布:大数据是以hadoop 编辑:程序博客网 时间:2024/06/14 20:44

Identity of entities is defined by their primary keys. Since firstname and lastname are not parts of the primary key, you cannot tell JPA to treat Users with the same firstnames and lastnames as equal if they have different userIds.

So, if you want to update a User identified by its firstname and lastname, you need to find that User by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don’t need to do anything to save these changes explicitly.

持久化的两种方式

  • 使用native query,明确调用Insert或Update API进行相应的插入或更新操作

  • 工作单元的方式:由持久化库(Entity Manager)托管一系列对象集合,当工作单元完成时(比如:典型的案例是某个特定事务提交)针对集合中所有对象的修改操作将自动更新到数据库中。当需要插入数据库对象时,你要确保相应的对象由持久化库进行(Entity Manager)托管,托管对象由主键标识区分,如果你为一个对象指定了预定义的主键,那么其将自动关联数据库中对应主键的记录,托管对象的状态会自动更新到数据库记录中。

    JPA持久化采取的是第二种方式

    @Transactional    public T save(T entity) {             if (entityInformation.isNew(entity)) {                    em.persist(entity);                    return entity;            } else {                    return em.merge(entity);            }    }

The save(…) method of the CrudRepository interface is supposed to abstract simply storing an entity no matter what state it is in. Thus it must not expose the actual store specific implementation, even if (as in the JPA) case the store differentiates between new entities to be stored and existing ones to be updated. That’s why the method is actually called save(…) not create(…) or update(…). We return a result from that method to actually allow the store implementation to return a completely different instance as JPA potentially does when merge(…) gets invoked.

So generally it’s more of an API decision to be lenient regarding the actual implementation and thus implementing the method for JPA as we do. There’s no additional proxy massaging done to the entities passed.

https://stackoverflow.com/questions/11881479/how-do-i-update-an-entity-using-spring-data-jpa

https://stackoverflow.com/questions/8625150/why-to-use-returned-instance-after-save-on-spring-data-jpa-repository