Implementing MyBatis Encryption with a Custom TypeHandler for Automatic Phone Number Encryption/Decryption
This article demonstrates how to protect sensitive user data such as phone numbers in a MySQL database by creating a custom MyBatis TypeHandler that automatically encrypts values on insert and decrypts them on query using AES encryption from the Hutool library.
Introduction : The article introduces a simple method to encrypt and decrypt data in MyBatis, which is rarely discussed in daily development, and suggests skipping the article if you are already familiar with the approach.
Background : Storing sensitive information like phone numbers or bank cards in plain text is insecure; a database breach or data export by a former employee could expose this data. Therefore, an encryption solution is required.
Solution : Because the project uses MyBatis as the persistence layer, the author chooses to implement a custom TypeHandler (instead of a plugin) to handle encryption and decryption automatically.
Requirements : In the customer table, the phone column must be stored encrypted while the address column remains plain. The system should encrypt the phone number when inserting a new customer and decrypt it when querying.
Implementation Steps :
Create an entity class Encrypt that wraps a String value and provides getters and setters.
public class Encrypt {
private String value;
public Encrypt() {}
public Encrypt(String value) { this.value = value; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}Implement a custom EncryptTypeHandler extending BaseTypeHandler<Encrypt> . It uses Hutool's AES with a fixed 16‑byte key to encrypt the value in setNonNullParameter and decrypt it in the three getNullableResult overloads.
package com.huan.study.mybatis.typehandler;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.nio.charset.StandardCharsets;
import java.sql.*;
/**
* Encryption TypeHandler
*/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Encrypt.class)
public class EncryptTypeHandler extends BaseTypeHandler
{
private static final byte[] KEYS = "12345678abcdefgh".getBytes(StandardCharsets.UTF_8);
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null || parameter.getValue() == null) {
ps.setString(i, null);
return;
}
AES aes = SecureUtil.aes(KEYS);
String encrypt = aes.encryptHex(parameter.getValue());
ps.setString(i, encrypt);
}
@Override
public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
return decrypt(rs.getString(columnName));
}
@Override
public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return decrypt(rs.getString(columnIndex));
}
@Override
public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return decrypt(cs.getString(columnIndex));
}
public Encrypt decrypt(String value) {
if (value == null) return null;
return new Encrypt(SecureUtil.aes(KEYS).decryptStr(value));
}
}Configure the MyBatis mapper XML to map the phone column to the Encrypt type via the custom TypeHandler.
<?xml version="1.0" encoding="UTF-8"?>
insert into customer(phone,address) values (#{phone},#{address})
select * from customer where phone = #{phone}Specify the package containing the TypeHandler in the MyBatis configuration:
mybatis.type-handlers-package=com.huan.study.mybatis.typehandlerImplement simple service methods for adding a customer and querying by phone number (code omitted for brevity).
Testing : After inserting a record, the phone column in the database stores the encrypted hex string. When querying, the TypeHandler automatically decrypts the value, returning the original phone number.
All source code and a complete demo project are available at the provided Gitee repository links.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.