SimpleJpaRepositoryImpl.java
2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.erry.iclear.dateInterface.service;
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.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* @author Administrator
*/
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(rollbackFor = Exception.class)
public <S extends T> S save(S entity) {
//获取ID
ID entityId = (ID) entityInformation.getId(entity);
Optional<T> optionalT;
if (StringUtils.isEmpty(entityId)) {
optionalT = Optional.empty();
} else {
optionalT = findById(entityId);
}
//获取空属性并处理成null
String[] nullProperties = getNullProperties(entity);
//若根据ID查询结果为空
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]);
}
}