【笔记】MyBatisPlus实现自定义类型转换

前言

MyBatisPlus实现自定义类型转换

定义TypeHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class IntToBooleanTypeHandler implements TypeHandler<Boolean> {

@Override
public void setParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
// 将 boolean 转换为 int 并设置到 PreparedStatement 中
ps.setInt(i, parameter ? 1 : 0);
}

@Override
public Boolean getResult(ResultSet rs, String columnName) throws SQLException {
// 从 ResultSet 中获取 int 值并转换为 boolean
int value = rs.getInt(columnName);
return value == 1;
}

@Override
public Boolean getResult(ResultSet rs, int columnIndex) throws SQLException {
// 从 ResultSet 中获取 int 值并转换为 boolean
int value = rs.getInt(columnIndex);
return value == 1;
}

@Override
public Boolean getResult(CallableStatement cs, int columnIndex) throws SQLException {
// 从 CallableStatement 中获取 int 值并转换为 boolean
int value = cs.getInt(columnIndex);
return value == 1;
}
}

在PO实体类中使用TypeHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.model;

import com.baomidou.mybatisplus.annotation.TableField;
import com.handler.IntToBooleanTypeHandler;
import lombok.Data;

@Data
public class Entity {

@TableField(typeHandler = IntToBooleanTypeHandler.class)
private Boolean flag;

}

完成