重点:application.propertis配置类
#TypeEnumHandler 这个类的包名,不是全路径
mybatis.type-handlers-package=com.fan.test.handler
两个枚举类:
public enum StatusEnum {DELETED(0),ACTIVE(1);private final int code;StatusEnum(int code) {this.code = code;}public int getCode() {return code;}
}
public enum TypeEnum {ONE(1, "one"),TWO(2, "two"),THREE(3, "three");private int code;private String desc;TypeEnum(int code, String desc) {this.code = code;this.desc = desc;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getDesc() {return desc;}public static TypeEnum fromCode(int code) {for (TypeEnum type : values()) {if (type.code == code) {return type;}}throw new IllegalArgumentException("Invalid TypeEnum code: " + code);}
}
实体类:
@Data
public class User {private Long id;private TypeEnum type;private String username;private String password;
}
handler 转换类【TypeEnumHandler】
@MappedTypes(TypeEnum.class)
@MappedJdbcTypes(JdbcType.INTEGER)
public class TypeEnumHandler implements TypeHandler<TypeEnum> {@Overridepublic void setParameter(PreparedStatement ps, int i, TypeEnum parameter, JdbcType jdbcType) throws SQLException {System.out.println("TypeHandler called with value: " + parameter);ps.setInt(i, parameter.getCode());}@Overridepublic TypeEnum getResult(ResultSet rs, String columnName) throws SQLException {return TypeEnum.fromCode(rs.getInt(columnName));}@Overridepublic TypeEnum getResult(ResultSet rs, int columnIndex) throws SQLException {return TypeEnum.fromCode(rs.getInt(columnIndex));}@Overridepublic TypeEnum getResult(CallableStatement cs, int columnIndex) throws SQLException {return TypeEnum.fromCode(cs.getInt(columnIndex));}
}
mapper接口
@Mapper
public interface UserMapper {List<User> selectAll();void insertUser(User user);
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="UserMapper"><!--查询(自动映射)--><select id="selectAll" resultType="com.fan.test.entity.User"><bind name="ACTIVE" value="@com.fan.test.enums.StatusEnum@ACTIVE.code"/>SELECT * FROM user WHERE status = #{ACTIVE}</select><!--插入(自动传入枚举的 code)--><insert id="insertUser" parameterType="com.fan.test.entity.User">INSERT INTO user (type, username, password)VALUES (#{type}, #{username}, #{password})</insert>
</mapper>
这里枚举转换还有其他两种写法:
第一种:
@TypeHandler(TypeEnumHandler.class)private TypeEnum type;
第二种:
<insert id="insertUser" parameterType="com.fan.test.entity.User">INSERT INTO user (type, username, password)VALUES (#{type, typeHandler=com.fan.test.handler.TypeEnumHandler}, #{username}, #{password})
</insert>