SpringBoot 實現(xiàn)JPA的save方法不更新null屬性

1.問題描述
直接調(diào)用jpa原生save方法會導(dǎo)致null屬性覆蓋數(shù)據(jù)庫之前的值
2.解決思路
如果現(xiàn)在保存某對象,首先根據(jù)主鍵查詢這個對象的最新對象,然后將此對象的非空屬性覆蓋到最新對象。
直接修改通用JpaRepository的實現(xiàn)類,然后在啟動類標(biāo)記此實現(xiàn)類即可。
3.需要添加的代碼

  • 新建類SimpleJpaRepositoryImpl:
package com.xzp.config;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.util.StringUtils;

/**
 * @author xzp
 * @date 2020-05-21 13:26:58
 */
public class SimpleJpaRepositoryImpl<T, ID> extends SimpleJpaRepository<T, ID> {

    private final JpaEntityInformation<T, ?> entityInformation;
    private final EntityManager em;

    @Autowired
    public SimpleJpaRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityInformation = entityInformation;
        this.em = entityManager;
    }

    /**
     * 通用save方法 :新增/選擇性更新
     */
    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public <S extends T> S save(S entity) {
        // 獲取ID
        ID entityId = (ID) entityInformation.getId(entity);
        Optional<T> optionalT;
        if (StringUtils.isEmpty(entityId)) {
            String uuid = UUID.randomUUID().toString();
            // 防止UUID重復(fù)
            if (findById((ID) uuid).isPresent()) {
                uuid = UUID.randomUUID().toString();
            }
            // 若ID為空 則設(shè)置為UUID
            new BeanWrapperImpl(entity).setPropertyValue(entityInformation.getIdAttribute().getName(), uuid);
            // 標(biāo)記為新增數(shù)據(jù)
            optionalT = Optional.empty();
        } else {
            // 若ID非空 則查詢最新數(shù)據(jù)
            optionalT = findById(entityId);
        }
        // 獲取空屬性并處理成null
        String[] nullProperties = getNullProperties(entity);
        // 若根據(jù)ID查詢結(jié)果為空
        if (!optionalT.isPresent()) {
            em.persist(entity);// 新增
            return entity;
        } else {
            // 1.獲取最新對象
            T target = optionalT.get();
            // 2.將非空屬性覆蓋到最新對象
            BeanUtils.copyProperties(entity, target, nullProperties);
            // 3.更新非空屬性
            em.merge(target);
            return entity;
        }
    }

    /**
     * 獲取對象的空屬性
     */
    private static String[] getNullProperties(Object src) {
        // 1.獲取Bean
        BeanWrapper srcBean = new BeanWrapperImpl(src);
        // 2.獲取Bean的屬性描述
        PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
        // 3.獲取Bean的空屬性
        Set<String> properties = new HashSet<>();
        for (PropertyDescriptor propertyDescriptor : pds) {
            String propertyName = propertyDescriptor.getName();
            Object propertyValue = srcBean.getPropertyValue(propertyName);
            if (StringUtils.isEmpty(propertyValue)) {
                srcBean.setPropertyValue(propertyName, null);
                properties.add(propertyName);
            }
        }
        return properties.toArray(new String[0]);
    }
}
  • 啟動類修改EnableJpaRepositories注解,添加repositoryBaseClass:
@EnableJpaRepositories(value = "com.xzp.repository", repositoryBaseClass = SimpleJpaRepositoryImpl.class)

只需以上兩個修改即可實現(xiàn)我們的需求。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容