詳解SpringBoot實(shí)現(xiàn)JPA的save方法不更新null屬性
序言:直接調(diào)用原生Save方法會(huì)導(dǎo)致null屬性覆蓋到數(shù)據(jù)庫,使用起來十分不方便。本文提供便捷方法解決此問題。
核心思路
如果現(xiàn)在保存某User對(duì)象,首先根據(jù)主鍵查詢這個(gè)User的最新對(duì)象,然后將此User對(duì)象的非空屬性覆蓋到最新對(duì)象。
核心代碼
直接修改通用JpaRepository的實(shí)現(xiàn)類,然后在啟動(dòng)類標(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.獲取最新對(duì)象
T target = optionalT.get();
//2.將非空屬性覆蓋到最新對(duì)象
BeanUtils.copyProperties(entity, target, nullProperties);
//3.更新非空屬性
em.merge(target);
return entity;
}
}
/**
* 獲取對(duì)象的空屬性
*/
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]);
}
}
二、啟動(dòng)類
@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');
六、測(cè)試代碼
@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。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳細(xì)理解JAVA面向?qū)ο蟮姆庋b,繼承,多態(tài),抽象
這篇文章主要介紹了Java基礎(chǔ)之面向?qū)ο髾C(jī)制(多態(tài)、繼承)底層實(shí)現(xiàn),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-07-07
Spring Cloud OpenFeign REST服務(wù)客戶端原理及用法解析
這篇文章主要介紹了Spring Cloud OpenFeign REST服務(wù)客戶端原理及用法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
SpringBoot超詳細(xì)講解自動(dòng)配置原理
在進(jìn)行項(xiàng)目編寫前,我們還需要知道一個(gè)東西,就是SpringBoot對(duì)我們的SpringMVC還做了哪些配置,包括如何擴(kuò)展,如何定制,只有把這些都搞清楚了,我們?cè)谥笫褂貌艜?huì)更加得心應(yīng)手2022-06-06
java實(shí)現(xiàn)簡(jiǎn)單的圖書借閱系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單的圖書借閱系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
SpringBoot使用prometheus監(jiān)控的示例代碼
這篇文章主要介紹了SpringBoot使用prometheus監(jiān)控的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
java web開發(fā)之購(gòu)物車功能實(shí)現(xiàn)示例代碼
這篇文章主要介紹了java web開發(fā)之購(gòu)物車功能實(shí)現(xiàn)示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10

