save() 方法
Spring Data JPA 写入数据可以通过CrudRepository
的save()
方法来实现。
public interface CrudRepository<T, ID> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be {@literal null}.
* @return the saved entity; will never be {@literal null}.
* @throws IllegalArgumentException in case the given {@literal entity} is {@literal null}.
*/
<S extends T> S save(S entity);
...
}
CrudRepository.save(...)
通过调用EntityManager.persist(...)
来实现插入一条新数据,通过调用EntityManager.merge(...)
来实现更新旧数据。那么,Spring Data 如何判断要插入新数据还是更新旧数据呢?
Entity 的保存策略
Spring Data JPA 通过以下几个策略来判断新增数据还是更新数据。
@Id 属性(主键)
- 如果 @Id 为
null
,则会新增一条数据 - 如果 @Id 为一个已存在的主键,则会修改该主键对应数据
- 如果 @Id 为一个不存在的主键值,则会抛出
ConstraintViolationException
异常
继承 Persistable
package org.springframework.data.domain;
import org.springframework.lang.Nullable;
/**
* Simple interface for entities.
* <p>
* Note that methods declared in this interface ({@link #getId()} and {@link #isNew()}) become property accessors when
* implementing this interface in combination with
* {@link org.springframework.data.annotation.AccessType @AccessType(PROPERTY)}. Either of these can be marked as
* transient when annotated with {@link org.springframework.data.annotation.Transient @Transient}.
*
* @param <ID> the type of the identifier
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
*/
public interface Persistable<ID> {
/**
* Returns the id of the entity.
*
* @return the id. Can be {@literal null}.
*/
@Nullable
ID getId();
/**
* Returns if the {@code Persistable} is new or was persisted already.
*
* @return if {@literal true} the object is new.
*/
boolean isNew();
}
如果isNew()
返回了true
,则会插入一条新数据,反之,修改ID
对应的旧数据。
实现 EntityInformation
不推荐。
飞鱼原创 https://ffish.net,未经允许,严禁转载!