调用设置器时,Hibernate更新数据



我在数据库中具有加密值,我想在发送到前端之前将其解密。当我首先将值保存为加密时,它看起来像数据库中的-kKwj477382jle34nw。但是,如果我调用我在此函数中进行解密的 getClientByUsername()函数,则数据库中的值在将对象发送到前端之前,当我在对象中设置解密值时,数据库中的值也会自动更改。

@Transactional
public ResponseEntity <Client> getClientByUsername(String username) throws Exception {
  Client loggedClient = clientDAO.findByUsername(username);
  String data = loggedClient.getCreditCardNo();
  if (null != data) {
    @SuppressWarnings("static-access")
    byte[] encrypted = base64.decodeBase64(data);
    SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey.getBytes(), algorithm);
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    decrypted = cipher.doFinal(encrypted);
    loggedClient.setCreditCardNo(new String(decrypted));
  }
  return new ResponseEntity < Client > (loggedClient, HttpStatus.OK);
}

这是我保存值为加密的值的方式:

@Transactional
public boolean clientUpdate(String client) {
    str = updateclient.getCreditCardNo();
    if (null != str) {
      SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), algorithm);
      Cipher cipher = Cipher.getInstance(algorithm);
      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
      encrypted = cipher.doFinal(str.getBytes("UTF-8"));
      updateclient.setCreditCardNo(base64.encodeToString(encrypted));
      return clientDAO.updateProfileClient(updateclient);
    }

如何在调用设置器时阻止Hibernate更改值?

update

@PersistenceContext
private EntityManager entityManager;
public Client findByUsername(String username) throws Exception {
      Query query = entityManager.createNamedQuery("Client.findByUsername");
      query.setParameter("username", username);
      List result = query.getResultList();
      return result.size() > 0 ? (Client) result.get(0) : null;
    }

您需要从Hibernate的会话中驱逐此对象:

void evict(Object object) throws HibernateException

从"会话缓存"中删除此实例。更改实例 不会与数据库同步。此操作级联到 相关实例是否与 cascade ="驱逐"。

P.S。只是想,您也可以考虑另一种方法。您可以在BEAN中创建一个字段,该字段将标记为@Transient,即与数据库分离,并将其命名为creditCardNoDecrypted。加密字段标记为@JsonIngore(或您用于序列化的任何内容)。

最新更新