序言:直接調(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。