JpaRepository 未曾定义update 方法只有save 相关接口。因自己项目需要update()更新实体。百度了很多方法,最终完美解决。忘记是那篇博客了所以未注明转载出处。
解决办法:1.自己实现SimpleJpaRepository如下
public class SimpleJpaRepositoryImpl <T, ID> extends SimpleJpaRepository<T, ID> {private final JpaEntityInformation<T, ?> entityInformation;private final EntityManager em;@Autowiredpublic SimpleJpaRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {super(entityInformation, entityManager);this.entityInformation = entityInformation;this.em = entityManager;}/*** 通用save方法 :新增/选择性更新*/@Override@Transactionalpublic <S extends T> S save(S entity) {//获取IDID entityId = (ID) entityInformation.getId(entity);Optional<T> optionalT;if (StringUtils.isEmpty(entityId)) {String uuid = UUIDUtils.getUUID();//防止UUID重复if (findById((ID) uuid).isPresent()) {uuid = UUIDUtils.getUUID();}//若ID为空 则设置为UUIDnew BeanWrapperImpl(entity).setPropertyValue(entityInformation.getIdAttribute().getName(), uuid);//标记为新增数据optionalT = Optional.empty();} else {//若ID非空 则查询最新数据optionalT = findById(entityId);}//获取空属性并处理成nullString[] 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.获取BeanBeanWrapper 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]);}
2.在启动类中标记

即可。
文章转载自精准丶优雅,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




