Mybatis-BaseTypeHandler实现Dao层数据加解密

Mybatis官方文档

需求:数据库保存的数据需要加密,然后查询的时候解密

具体方法:继承BaseTypeHandler,然后重写具体的set、get方法

    public abstract void setNonNullParameter(PreparedStatement var1, int var2, T var3, JdbcType var4) throws SQLException;

    public abstract T getNullableResult(ResultSet var1, String var2) throws SQLException;

    public abstract T getNullableResult(ResultSet var1, int var2) throws SQLException;

    public abstract T getNullableResult(CallableStatement var1, int var2) throws SQLException;

1、Mybatis在执行Insert语句时,先创建PreparedStatement对象,然后通过setXXX方法给占位符设置对应的值,而重写setNonNullParameter方法的目的就是set的值=加密之后的值,其中setNonNullParameter(PreparedStatement var1, int var2, T var3, JdbcType var4), var2:参数下标(从0开始),var3:对应参数(待加密的值)

2、getNullableResult(ResultSet var1, String var2),在查询的时候解密

测试表:

create table customer_info_demo
(
  id           bigint auto_increment
  comment 'id'
    primary key,
  customer_id  varchar(32)                        not null
  comment '用户ID',
  card_id      varchar(32)                        not null
  comment '身份证号',
  created_time datetime default CURRENT_TIMESTAMP null
  comment 'created time',
  updated_time datetime default CURRENT_TIMESTAMP null
  on update CURRENT_TIMESTAMP
  comment 'updated time'
)
  comment '用户信息表'
  collate = utf8mb4_unicode_ci;

加密解密工具类:

package com.sentinel.demo.sentinel.handler;

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;

/**
 * Created by yanshao on 2020-03-06.
 */
public class CustomerDataHandler extends BaseTypeHandler<String> {
    /**
     * Insert时
     * */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex,String value,JdbcType jdbcType) throws SQLException {
        System.out.println("加密setNonNullParameter");
        preparedStatement.setString(columnIndex,"加密>>>" + value);
    }

    /**
     * 查询
     * */
    @Override
    public String getNullableResult(ResultSet resultSet,String columnName) throws SQLException {
        System.out.println("解密getNullableResult>>>");
        return resultSet.getString(columnName).split(">>>")[1];
    }

    /**
     * 查询
     * */
    @Override
    public String getNullableResult(ResultSet resultSet,int columnIndex) throws SQLException {
        System.out.println("解密getNullableResult>>>");
        return resultSet.getString(columnIndex).split(">>>")[1];
    }

    /**
     * 查询
     * */
    @Override
    public String getNullableResult(CallableStatement callableStatement,int i) throws SQLException {
        return null;
    }
}

对应bean:

package com.sentinel.demo.sentinel.bean;

import lombok.Data;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.LocalDateTime;

@Data
public class CustomerInfoDemo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @NotNull
    private Long id;

    /**
     * 用户ID
     */
    @NotNull
    @Size(max = 32)
    private String customerId;

    /**
     * 身份证号
     * */
    @Size(max = 64)
    private String cardId;

    /**
     * 创建时间
     */
    private LocalDateTime createdTime;

    /**
     * 修改时间
     */
    private LocalDateTime updatedTime;
}

mapper:

package com.sentinel.demo.sentinel.mapper;

import com.sentinel.demo.sentinel.bean.CustomerInfoDemo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface CustomerInfoDemoMapper {
    int insert(CustomerInfoDemo customerInfoDemo);

    List<CustomerInfoDemo> selectAll();

    CustomerInfoDemo selectByCardId(@Param("cardId") String cardId);

    CustomerInfoDemo selectByCustomerId(@Param("customerId") String customerId);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sentinel.demo.sentinel.mapper.CustomerInfoDemoMapper">
    <resultMap id="BaseResultMap" type="com.sentinel.demo.sentinel.bean.CustomerInfoDemo">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="customer_id" jdbcType="VARCHAR" property="customerId"/>
        <result column="card_id" jdbcType="VARCHAR" property="cardId" typeHandler= "com.sentinel.demo.sentinel.handler.CustomerDataHandler"/>
        <result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
        <result column="updated_time" jdbcType="TIMESTAMP" property="updatedTime" />
    </resultMap>


    <sql id="Base_Column_List">
        id, customer_id, card_id,created_time, updated_time
    </sql>

    <insert id="insert" parameterType="com.sentinel.demo.sentinel.bean.CustomerInfoDemo">
        insert into customer_info_demo (customer_id,card_id)
        values (
          #{customerId,jdbcType=VARCHAR},
          #{cardId,jdbcType=VARCHAR,typeHandler=com.sentinel.demo.sentinel.handler.CustomerDataHandler}
          )
    </insert>

    <select id="selectAll" resultMap="BaseResultMap">
        select
         <include refid="Base_Column_List" />
        from customer_info_demo
    </select>

    <select id="selectByCardId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from customer_info_demo
        where card_id =  #{cardId,jdbcType=VARCHAR,typeHandler=com.sentinel.demo.sentinel.handler.CustomerDataHandler}
    </select>

    <select id="selectByCustomerId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from customer_info_demo
        where customer_id = #{customerId,jdbcType=VARCHAR}
    </select>
</mapper>

测试1:

    @Test
    public void insert() {
        CustomerInfoDemo customerInfoDemo = new CustomerInfoDemo();
        customerInfoDemo.setCustomerId("123456");
        customerInfoDemo.setCardId("411288199610011234");
        customerInfoDemoMapper.insert(customerInfoDemo);

    }

测试2:

@Test
    public void selectAll() {
        List<CustomerInfoDemo> customerInfoDemos = customerInfoDemoMapper.selectAll();
        customerInfoDemos.forEach(customerInfoDemo -> {
            System.out.println("CustomerInfoDemo>>>" + customerInfoDemo);
        });
    }

测试3:

    @Test
    public void selectByCardId(){
        CustomerInfoDemo customerInfoDemo = customerInfoDemoMapper.selectByCardId("411288199610011234");
        System.out.println("customerInfoDemo>>>" + customerInfoDemo);
    }

 

 

 

 

Mybatis-Plus 是 Mybatis 的增强工具,在 Mybatis 的基础上,提供了更加便捷的操作方式和更加强大的功能。使用 Mybatis-Plus 替换 DAO 可以极大地提高开发效率和代码质量。 以下是使用 Mybatis-Plus 替换 DAO 的步骤: 1. 添加依赖 在 pom.xml 文件中添加 Mybatis-Plus 的依赖: ```xml <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> ``` 2. 配置 Mybatis-Plus 在 application.yml 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: # mapper 文件位置 mapper-locations: classpath:/mapper/**/*.xml # 实体类扫描路径 typeAliasesPackage: com.example.entity ``` 3. 创建实体类 使用 Mybatis-Plus 需要创建实体类,并且实体类需要继承 BaseMapper 接口。例如: ```java public interface UserMapper extends BaseMapper<User> { } ``` 4. 使用 Mybatis-Plus 进行 CRUD 操作 使用 Mybatis-Plus 进行 CRUD 操作非常简单,只需要在 Service 中调用相应的方法即可。例如: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } @Override public List<User> getUserList() { return userMapper.selectList(null); } @Override public int addUser(User user) { return userMapper.insert(user); } @Override public int updateUser(User user) { return userMapper.updateById(user); } @Override public int deleteUser(Long id) { return userMapper.deleteById(id); } } ``` 以上就是使用 Mybatis-Plus 替换 DAO 的步骤,使用 Mybatis-Plus 可以极大地简化 DAO 的开发,提高代码质量和开发效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

燕少༒江湖

给我一份鼓励!谢谢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值