一直从数据库获取数据后如何解码值

How to decode values after getting data from db all the time

我想在每次获取数据时解码一些值,并在将新数据持久化到数据库时进行编码。

我不想在模型 class 中使用我的编码和解码逻辑。

任何人都可以建议我使用任何拦截器或其他方法来解决这个问题吗?

我以前发过这个,但在这里也适用:

@around(value="execution(* db.entities.package)")
public void cypher(ProceedingJoinPoint call){
   try {
     // encode or decode logic here
     call.proceed();
   } catch (Exception e){
      // handle exception
   }
}

你可以使用 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 方法。