作者:转身-说离别2013 | 来源:互联网 | 2023-10-12 15:06
因此,我想使生活更轻松的是创建一个注释,以标记我有兴趣比较的字段。没有,我最终不得不坚持命名对话,就像仅使用以’get’开头的方法一样。我发现这种方法有很多极端的情况。
注释。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AuditCompare {
public String name() default "";
public CompareType compareBy() default CompareType.string;
enum CompareType {
string, count
}
}
像这样被使用
@Entity
@Audited
public class Guideline {
.....
@AuditCompare
private String name;
@AuditCompare
private String owner;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval=true, mappedBy="guideline")
private Set checklistItems = new HashSet();
.........
}
由于envers将Set更改和Set的对象都审核为两个不同的事件,因此我不想比较是否更改了set。然后做比较,我有看起来像的方法
private void findMatchingValues(Object oldInstance, Object newInstance, activityEntry entry) {
try {
Class oldClass = oldInstance.getclass();
for (Field someField : oldClass.getDeclaredFields()) {
if (someField.isAnnotationPresent(AuditCompare.class)) {
String name = someField.getannotation(AuditCompare.class).name();
name = name.equals("") ? someField.getName() : name;
Method method = oldClass.getDeclaredMethod(getGetterName(name));
if(someField.getannotation(AuditCompare.class).compareBy().equals(AuditCompare.CompareType.count)) {
int oldSize = getcollectionCount(oldInstance, method);
int newSize = getcollectionCount(newInstance, method);
if (oldSize != newSize) entry.addChangeEntry(name, oldSize, newSize);
} else {
Object oldValue = getObjectvalue(oldInstance, method);
Object newValue = getObjectvalue(newInstance, method);
if (!oldValue.equals(newValue)) entry.addChangeEntry(name, oldValue, newValue);
}
}
}
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}