1 、 这里我介绍如何使用枚举类型前后端自动转换的方法。(附上项目:Enum.zip)目录结构图如下图所示:
2 、pom.xml 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>SpringbootMybatisEnum</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
3、application.yml 文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.domain
configuration:
map-underscore-to-camel-case: true
default-enum-type-handler: com.typeHandler.BaseEnumTypeHandler
4 、创建BaseEnum
public interface BaseEnum<E extends Enum<?>, T> {
T getValue();
}
5 、创建BaseEnumTypeHandler 并继承 BaseTypeHandler
public class BaseEnumTypeHandler<E extends Enum<E> & BaseEnum> extends BaseTypeHandler<E> {
private Class<E> enumType;
private Map<Object, E> enumMap = new HashMap<>();
public BaseEnumTypeHandler(Class<E> type) {
if (type == null)
throw new IllegalArgumentException("Type argument cannot be null");
this.enumType = type;
E[] enums = enumType.getEnumConstants();
if (enums == null)
throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
for (E e : enums) {
enumMap.put(e.getValue(), e);
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
ps.setObject(i, parameter.getValue());
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
return get(rs.getInt(columnName));
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return get(rs.getInt(columnIndex));
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return get(cs.getInt(columnIndex));
}
private E get(Integer v) {
if (v == null) {
return null;
}
return this.enumMap.get(v);
}
}
6、创建枚举转换工厂 BaseEnumConverterFactory
/**
* 枚举类型转换工厂
*/
public class BaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
@SuppressWarnings("rawtypes")
private static final Map<Class, Converter> converterMap = new WeakHashMap<>();
@SuppressWarnings({
"rawtypes", "unchecked" })
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
Converter result = converterMap.get(targetType);
if(result == null) {
result = new IntegerStrToEnum<T>(targetType);
converterMap.put(targetType, result);
}
return result;
}
class IntegerStrToEnum<T extends BaseEnum> implements Converter<String, T> {
@SuppressWarnings("unused")
private final Class<T> enumType;
private Map<String, T> enumMap = new HashMap<>();
public IntegerStrToEnum(Class<T> enumType) {
this.enumType = enumType;
T[] enums = enumType.getEnumConstants();
for(T e : enums) {
enumMap.put(e.getValue() + "", e);
}
}
@Override
public T convert(String source) {
T result = enumMap.get(source);
if(result == null) {
throw new IllegalArgumentException("No element matches " + source);
}
return result;
}
}
}
7、新建User实体类
public class User {
private String id;
private String name;
private Sex sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
}
8、创建Sex 枚举类
public enum Sex implements BaseEnum{
MALE(1, "男"),
FEMALE(0, "女");
private Integer value;
private String description;
private Sex(int value, String description) {
this.value = value;
this.description = description;
}
@Override
public Integer getValue() {
return value;
}
public String getDescription() {
return description;
}
}
9、创建UserController
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/insert")
public void Add(User user) {
userMapper.insert(user);
}
@RequestMapping("/findAll")
public List<User> list() {
List<User> list = userMapper.findAll();
return list;
}
}
10、创建 UserMapper
@Mapper
public interface UserMapper {
public List<User> findAll();
public int insert(User user);
}
11、创建 UserMapper.xml
<?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.mapper.UserMapper">
<resultMap id="UserResultMap" type="com.domain.User">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="INTEGER" property="sex" />
</resultMap>
<select id="findAll" resultMap="UserResultMap">
SELECT * from USER
</select>
<insert id="insert" parameterType="com.domain.User">
INSERT INTO user ( name, sex)
VALUES
(
#{
name,jdbcType=VARCHAR},
#{
sex,jdbcType=INTEGER}
)
</insert>
</mapper>