sql 的动态更新插入
mybatis 中可以在sql语句中使用isNull来判断
jap中的实现方法
@Entity
@Data
@Table(name = "channel")
// 需要在实体类中加入
@EntityListeners(AuditingEntityListener.class)
public class Channel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long channelId;
@CreationTimestamp
private Timestamp createTime;
@CreatedBy
private String createUserId;
@UpdateTimestamp
private Timestamp modifyTime;
@LastModifiedBy
private String modifyUserId;
}
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaAuditingConfiguration {
@Bean
public AuditorAware<String> auditorProvider() {
//获取当前用户 在create的时候使用
return () -> Optional.ofNullable( SecurityContextHolder.getContext().getAuthentication().getName());
}
}
@PostMapping(value = "/create")
protected ResponseEntity create(@RequestBody Channel resources) {
if (!ObjectUtils.isEmpty(resources.getChannelId())) {
Channel channel = phoneChannelService.getInfo(resources.getChannelId()).get();
resources.setCreateTime(channel.getCreateTime());
resources.setCreateUserId(channel.getCreateUserId());
BeanUtils.copyProperties(resources, channel, ResultUtil.getNullPropertyNames(resources));
resources = channel;
}
return ResultUtil.wrapper(phoneChannelService.save(resources), HttpStatus.OK);
}
/**
* 获取属性为null的字段列表
* @date: 2019-06-10 liu
**/
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
.toArray(String[]::new);
}
}