欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis自定义TypeHandler处理枚举类型的字段

程序员文章站 2022-04-23 15:53:10
...

首先看一下我们的实体类的sql

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `sex` int(10) DEFAULT NULL,
  `mobile` varchar(20) NOT NULL,
  `tel` varchar(20) DEFAULT NULL,
  `email` varchar(60) DEFAULT NULL,
  `note` varchar(512) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

实体类


public class User {
	private Long id;
	private String userName;
	private String password;
	private SexEnum sex;
	private String mobile;
	private String tel;
	private String email;
	private String note;
#getter和setter省略
}

性别枚举类


public enum SexEnum {
	MALE(1, "男"),
	FEMALE(0, "女");

	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	SexEnum(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public static SexEnum getSexById(int id) {
		for (SexEnum sex : SexEnum.values()) {
			if (sex.getId() == id) {
				return sex;
			}
		}
		return null;
	}
}

自定义枚举类型typeHandler,需要继承TypeHandler并且标明需要处理的类型,该例子的类型为SexEnum


public class SexEnumTypeHandler implements TypeHandler<SexEnum> {

    Logger logger = Logger.getLogger(SexEnumTypeHandler.class);
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, SexEnum sexEnum, JdbcType jdbcType) throws SQLException {
        logger.info("设置string参数【" + sexEnum + "】");
        preparedStatement.setInt(i,sexEnum.getId());
    }

    @Override
    public SexEnum getResult(ResultSet resultSet, String s) throws SQLException {
        logger.info("获取string参数1【" + s + "】");
        int i = resultSet.getInt(s);
        return SexEnum.getSexById(i);
    }

    @Override
    public SexEnum getResult(ResultSet resultSet, int i) throws SQLException {
        logger.info("获取string参数2【" + resultSet.getInt(i) + "】");
        return SexEnum.getSexById(resultSet.getInt(i));
    }

    @Override
    public SexEnum getResult(CallableStatement callableStatement, int i) throws SQLException {
        logger.info("获取string参数3【" + callableStatement.getInt(i) + "】");
        return SexEnum.getSexById(callableStatement.getInt(i));
    }
}

mapper映射文件

public interface UserMapper {
	public User getUser(Long id);
}
<?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.framework.modules.mybatis2.mapper.UserMapper">
	<resultMap id="userMapper" type="user">
		<result property="id" column="id" />
		<result property="userName" column="user_name" />
		<result property="password" column="password" />
		<result property="sex" column="sex" 
            typeHandler="com.framework.modules.mybatis2.typehandler.SexEnumTypeHandler"/>
		<result property="mobile" column="mobile" />
		<result property="tel" column="tel" />
		<result property="email" column="email" />
		<result property="note" column="note" />
	</resultMap>
	<select id="getUser" resultMap="userMapper" parameterType="long">
	  select id, user_name, password, sex, mobile, tel, email, note from t_user 
      where id = #{id}
	</select>
</mapper>

测试

        SqlSession sqlSession = null;
		try {
			sqlSession = SqlSessionFactoryUtils.openSqlSession();
			UserMapper userMapper  = sqlSession.getMapper(UserMapper.class);
			User user = userMapper.getUser(1L);
			System.out.println(user.getSex().getName());
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

日志

DEBUG 2019-01-11 11:21:16,459 org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl: Opening JDBC Connection
DEBUG 2019-01-11 11:21:16,463 org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl: Setting autocommit to false on JDBC Connection [jdbc:mysql://localhost:3306/ssm, [email protected], MySQL Connector Java]
DEBUG 2019-01-11 11:21:16,468 org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl: ==>  Preparing: select id, user_name, password, sex, mobile, tel, email, note from t_user where id = ? 
DEBUG 2019-01-11 11:21:16,503 org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl: ==> Parameters: 1(Long)
 INFO 2019-01-11 11:21:16,572 com.framework.modules.mybatis2.typehandler.SexEnumTypeHandler: 获取string参数1【sex】
DEBUG 2019-01-11 11:21:16,573 org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl: <==      Total: 1
男

 

相关标签: MyBatis