数据库PostgreSQL,持久化框架SpringData-JPA
从CrudRepository到SimpleJpaRepository的save方法
@Transactional
public <S extends T> S save(S entity) {
if(this.entityInformation.isNew(entity)) {
this.em.persist(entity);
return entity;
} else {
return this.em.merge(entity);
}
}
看到CrudRepository有两个主要的实现类,SimpleJpaRepository和SimpleKeyValueRepository
走到SimpleJpaRepository的save方法,然后走JpaMetamodelEntityInformation的isNew
public boolean isNew(T entity) {
if(this.versionAttribute != null && !this.versionAttribute.getJavaType().isPrimitive()) {
BeanWrapper wrapper = new DirectFieldAccessFallbackBeanWrapper(entity);
Object versionValue = wrapper.getPropertyValue(this.versionAttribute.getName());
return versionValue == null;
} else {
return super.isNew(entity);
}
}
然后走super.isNew(),就是AbstractEntityInformation的isNew
public boolean isNew(T entity) {
ID id = this.getId(entity);
Class<ID> idType = this.getIdType();
if(!idType.isPrimitive()) {
return id == null;
} else if(id instanceof Number) {
return ((Number)id).longValue() == 0L;
} else {
throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", new Object[]{idType}));
}
}
this是JpaMetamodelEntityInformation;this.getIdType()在我这个实例中等于RelationCompositeKey,实体entity上使用@IdClas注解 ;而RelationCompositeKey没有实现isPrimitive()返回false,isNew返回false,所以最后走了meger方法。
贴部分实体代码
@IdClass(RelationCompositeKey.class)
public final class RelationEntity implements ToData<EntityRelation> {
@Id
@Column(name = RELATION_FROM_ID_PROPERTY)
private String fromId;
@Data
public class RelationCompositeKey implements Serializable {
@Transient
private static final long serialVersionUID = -4089175869616037592L;
private String fromId;
private String fromType;