JPA-PostgreSQL重复插入不报错

数据库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;

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值