MybatisPlus优雅实现加密?
MyBatis-Plus 本身不提供字段加密的功能,但你可以通过自定义TypeHandler来实现字段的加密和解密。
以下是一个简单的例子,展示了如何在MyBatis-Plus中实现自定义TypeHandler来处理加密字段:
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class EncryptTypeHandler extends BaseTypeHandler<String> {
private String encrypt(String input) {
// 实现加密逻辑
return input; // 假设这里进行了加密
}
private String decrypt(String input) {
// 实现解密逻辑
return input; // 假设这里进行了解密
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, encrypt(parameter));
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
String encrypted = rs.getString(columnName);
return decrypt(encrypted);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String encrypted = rs.getString(columnIndex);
return decrypt(encrypted);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String encrypted = cs.getString(columnIndex);
return decrypt(encrypted);
}
}
然后,你需要在MyBatis-Plus的配置中注册这个TypeHandler:
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan(basePackages = "你的mapper包路径")
public class MyBatisPlusConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(你的数据源);
MybatisConfiguration configuration =
评论已关闭