在更新未调用的实体@preUpdate方法时,我遇到了问题。
但是当我创建记录时,通过调用@prePersist方法可以使其正常工作。
Spring boot-2.1.4版本
我尝试通过创建其他事务来实现运气,但是如果我通过设置字段手动进行操作,它将像setMaskedDate(date);
这是我的实体
@Table(name = "PROCESS_SUBJECT")
@Data
public class ProcessSubject {
@Id
@Column(name = "ID", length = 50, unique = true, nullable = false, insertable = true, updatable = false)
private String id;
@Column(name = "SUBJECT_DATE", nullable = true, length = 100, columnDefinition = "varchar(100)")
private String encryptedSubjectDate;
// Subject Date (Hack instead of Transient since Transient has issues
//with Updates)
@Column(name = "SUBJ_DATE", insertable = false, updatable = false)
private Date subjectDate;
@Column(name = "MASKED_SUBJECT_DATE", nullable = true, length = 100)
private String maskedSubjectDate;
public void setSubjectDate(Date subjectDate) {
this.subjectDate = subjectDate;
this.encryptedSubjectDate = null;
}
@PrePersist
public void prePersist() {
this.id = StringUtil.getRandomUUID();
encrypt();
}
@PreUpdate
public void preUpdate() {
encrypt();
}
@PostLoad
public void postLoad() {
decrypt();
}
private void decrypt() {
if (StringUtils.isNotBlank(encryptedSubjectDate)) {
String subjectDateStr = EncryptUtil.aesDecrypt(encryptedSubjectDate, this.id);
try {
this.subjectDate = DateUtil.getDate(subjectDateStr, DateUtil.Patterns.ISO_DATE);
} catch (Exception e) {
this.subjectDate = new Date();
}
}
}
private void encrypt() {
if (subjectDate != null) {
String dateStr = DateUtil.printDateStr(subjectDate, DateUtil.Patterns.ISO_DATE);
this.encryptedSubjectDate = EncryptUtil.aesEncrypt(dateStr, this.id);
this.maskedSubjectDate = DateUtil.printDateStr(subjectDate, DateUtil.Patterns.MM_DD);
}}
}
这是交易内的代码
@Transactional
@Override
public void updateData(int id){
Optional<Language> languageOpt =languageRepository.findById(id);
if(languageOpt.isPresent()){
ProcessSubject subject = languageOpt.get().getSubject();
subject.setSubjectDate(new Date());
processSubjectRepository.save(subject);
}}
如果实体发生更新,我想调用crypto()方法。