spring-data-jpa 如何检测某个字段是否变动?
如题,在spring-data-jpa 框架中,是否存在一种较好的实践,能够非常方便的检测某个字段的变动。只需要写一个变化逻辑,而不需要自己写代码检测是否存在变动。有相关类似的功能可以提取出相关抽象也行。
回答:
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.PojoEntityTuplizer;
import org.springframework.util.ReflectionUtils;
public class TuplizerImpl extends PojoEntityTuplizer {
private final ConcurrentHashMap<Integer, Object[]> map = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Integer, Boolean> bMap = new ConcurrentHashMap<>();
public TuplizerImpl(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
super(entityMetamodel, mappedEntity);
}
@Override
public void setPropertyValues(Object entity, Object[] values) throws HibernateException {
if (bMap.containsKey(entity.hashCode()) && map.containsKey(entity.hashCode())) {
Arrays.stream(entity.getClass().getDeclaredFields())
.filter(f -> f.getAnnotation(Record.class) != null)
.peek(f -> f.setAccessible(true))
.map(s -> this.getEntityMetamodel().getPropertyIndex(s.getName()))
.filter(i -> !Objects.equals(map.get(entity.hashCode())[i], values[i]))
.map(i -> ReflectionUtils.findField(entity.getClass(),
this.getEntityMetamodel().getPropertyNames()[i])).filter(Objects::nonNull)
.map(f -> f.getAnnotation(Record.class))
.map(Record::field)
.map(s -> this.getEntityMetamodel().getPropertyIndex(s))
.forEach(i -> values[i] = new Date());
map.remove(entity.hashCode());
bMap.remove(entity.hashCode());
} else {
map.put(entity.hashCode(), values);
}
super.setPropertyValues(entity, values);
}
@Override
public void afterInitialize(Object entity, SharedSessionContractImplementor session) {
bMap.put(entity.hashCode(), true);
super.afterInitialize(entity, session);
}
}
@Entity@Getter
@Setter
@ToString
@Tuplizer(impl = TuplizerImpl.class)
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Record(field = "nameChange")
private String name;
@Setter(AccessLevel.NONE)
private Date nameChange;
@OneToMany( mappedBy = "fromAccount")
private Set<Transaction> transactions;
}
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Record {
String field() default "";
}
以上是 spring-data-jpa 如何检测某个字段是否变动? 的全部内容, 来源链接: utcz.com/p/944403.html