【发布时间】:2018-07-27 16:07:50
【问题描述】:
我想在每次获取数据时解码一些值,并在将新数据持久保存到数据库时进行编码。
我不想在 Model 类中使用我的编码和解码逻辑。
谁能建议我使用任何拦截器或其他方法来解决这个问题?
【问题讨论】:
-
AOP 将是一个不错的选择。如果使用 Spring,它是内置的。
标签: java spring interceptor
我想在每次获取数据时解码一些值,并在将新数据持久保存到数据库时进行编码。
我不想在 Model 类中使用我的编码和解码逻辑。
谁能建议我使用任何拦截器或其他方法来解决这个问题?
【问题讨论】:
标签: java spring interceptor
您也可以使用EntityListener。
您可以使用@PostLoad 注释来解码数据,使用@PrePersist、@PreUpdate 来持久化和更新数据。
例子:
@Component
class EntityListener {
@PrePersist
public void onPrePersist(Object o) {
// encode logic
}
@PreUpdate
public void onPreUpdate(Object o) {
// encode logic
}
@PostLoad
public void onPostLoad(Object o) {
// decode logic
}
}
@Table
@Entity
@EntityListeners({EntityListener.class})
class Model {
@Id
@Column(updatable = false)
@GeneratedValue
private int id;
private String password;
private String username;
}
每当使用 crud 操作时,总是根据它们的注解调用 EntityListener 方法。
【讨论】:
我之前发过这个,但是这里适用:
@around(value="execution(* db.entities.package)")
public void cypher(ProceedingJoinPoint call){
try {
// encode or decode logic here
call.proceed();
} catch (Exception e){
// handle exception
}
}
【讨论】: