【问题标题】:How to decode values after getting data from db all the time一直从db获取数据后如何解码值
【发布时间】:2018-07-27 16:07:50
【问题描述】:

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

我不想在 Model 类中使用我的编码和解码逻辑。

谁能建议我使用任何拦截器或其他方法来解决这个问题?

【问题讨论】:

  • AOP 将是一个不错的选择。如果使用 Spring,它是内置的。

标签: java spring interceptor


【解决方案1】:

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

【讨论】:

【解决方案2】:

我之前发过这个,但是这里适用:

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

【讨论】:

  • 如果您已将此作为答案发布,并且它确实适用,那么此问题与您回答的第一个问题重复,正确的行为是投票关闭此问题作为重复问题其他的。
  • 之前贴过代码sn-p,适用于另一个问题。
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多