溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-05-24 11:43:31 來源:億速云 閱讀:626 作者:小新 欄目:編程語言

這篇文章主要介紹SpringBoot如何實(shí)現(xiàn)JPA的save方法不更新null屬性,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

核心思路

如果現(xiàn)在保存某User對象,首先根據(jù)主鍵查詢這個User的最新對象,然后將此User對象的非空屬性覆蓋到最新對象。

核心代碼

直接修改通用JpaRepository的實(shí)現(xiàn)類,然后在啟動類標(biāo)記此實(shí)現(xiàn)類即可。

一、通用CRUD實(shí)現(xiàn)類

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方法 :新增/選擇性更新
   */
  @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(value = "com.hehe.repository", repositoryBaseClass = SimpleJpaRepositoryImpl.class)
@SpringBootApplication
public class JpaApplication {

  public static void main(String[] args) {
    SpringApplication.run(JpaApplication.class, args);
  }
}

三、實(shí)體類和通用Save

@Entity
@Table(name = "T_USER")
@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
public class User {
  @Id
  private String userId;
  private String username;
  private String password;
  //省略GET/SET
}
public interface UserRepository extends JpaRepository<User, String> {
}

四、配置文件 application.yml

spring:
 datasource:
  url: jdbc:mysql://localhost:3306/socks?useSSL=false
  username: root
  password: root
  driver-class-name: com.mysql.jdbc.Driver

五、數(shù)據(jù)庫腳本

drop table if exists t_user;
create table t_user (
 user_id varchar(50),
 username varchar(50),
 password varchar(50)
);

insert into t_user values ('1', 'admin', 'admin');
insert into t_user values ('2', 'yizhiwazi', '123456');

六、測試代碼

@RestController
public class UserController {

  @Autowired
  private UserRepository userRepository;

  @RequestMapping("/")
  public User get() {

    userRepository.save(new User("1", "", null));

    return userRepository.findById("1").get();
  }
}

整體結(jié)構(gòu)圖

在實(shí)際項(xiàng)目中,可以直接復(fù)制SimpleJpaRepositoryImpl使用,并不影響原有的其它API。

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

以上是“SpringBoot如何實(shí)現(xiàn)JPA的save方法不更新null屬性”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI