You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Hibernate至6:替换@TypeDef实现jasypt字段加密兼容方案咨询

Hibernate 6 替换废弃@TypeDef实现字段加密(基于Jasypt)

因为Hibernate 6废弃了@TypeDef和@Type注解,且Jasypt暂无适配Hibernate 6的专属包,推荐使用**JPA标准的@Convert+AttributeConverter**方案替代,无需依赖Hibernate专属类型,兼容性更好:

步骤1:实现加密转换类

自定义一个AttributeConverter,结合Jasypt的加密器完成字段的加密/解密逻辑:

import org.jasypt.util.text.StringEncryptor;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter(autoApply = false) // 仅手动指定字段应用,避免全局生效
public class EncryptedStringConverter implements AttributeConverter<String, String> {

    private final StringEncryptor encryptor;

    // 构造注入你原来配置的名为"encryptorUserName"的加密器
    public EncryptedStringConverter(StringEncryptor encryptorUserName) {
        this.encryptor = encryptorUserName;
    }

    // 实体属性转数据库存储值(加密)
    @Override
    public String convertToDatabaseColumn(String attribute) {
        return attribute == null ? null : encryptor.encrypt(attribute);
    }

    // 数据库值转实体属性(解密)
    @Override
    public String convertToEntityAttribute(String dbData) {
        return dbData == null ? null : encryptor.decrypt(dbData);
    }
}

步骤2:修改实体字段注解

移除原来的@Type和类上的@TypeDef,替换为@Convert注解:

@Column(name = "email")
@Email
@Convert(converter = EncryptedStringConverter.class)
@Override
public String getEmail() {
    return super.getEmail();
}

步骤3:确保加密器配置正确

保持你原来的Jasypt加密器配置(需与原encryptorUserName的参数一致,保证加密解密兼容性),比如Spring环境下的配置:

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.text.StringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JasyptConfig {

    @Bean(name = "encryptorUserName")
    public StringEncryptor stringEncryptor() {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword("your-encryption-key"); // 原加密密钥
        encryptor.setAlgorithm("PBEWithMD5AndDES"); // 原加密算法
        // 其他原配置参数(如盐值等)按需添加
        return encryptor;
    }
}

关键说明

  • 此方案基于JPA标准特性,Hibernate 6完全支持,无需依赖Jasypt的Hibernate专属插件
  • 加密逻辑与原EncryptedStringType完全一致,原有加密数据可正常解密
  • @Converter(autoApply = false)确保仅对指定字段生效,避免影响其他不需要加密的字段

内容的提问来源于stack exchange,提问作者Roland Gonczel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:45:06