码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis扩展之自定义类型处理器处理枚举类型

时间:2020-01-23 16:45:34      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:object   map   exce   public   ltm   rate   for   span   resultmap   

全局配置:

    <typeHandlers>
        <typeHandler handler="com.gong.mybatis.typeHandler.MyEnumEmpStatusTypeHandler"
        javaType="com.gong.mybatis.bean.EmpStatus"/>
        <!-- <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" 
        javaType="com.gong.mybatis.bean.EmpStatus"/> -->
    </typeHandlers>

MyEnumEmpStatusTypeHandler.java

package com.gong.mybatis.typeHandler;

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

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

import com.gong.mybatis.bean.EmpStatus;

/**
 * 1、实现TypeHandler接口。或者继承BaseTypeHandler
 *
 *
 */
public class MyEnumEmpStatusTypeHandler implements TypeHandler<EmpStatus> {

    /**
     * 定义当前数据如何保存到数据库中
     */
    @Override
    public void setParameter(PreparedStatement ps, int i, EmpStatus parameter,
            JdbcType jdbcType) throws SQLException {
        // TODO Auto-generated method stub
        System.out.println("要保存的状态码:"+parameter.getCode());
        ps.setString(i, parameter.getCode().toString());
    }

    @Override
    public EmpStatus getResult(ResultSet rs, String columnName)
            throws SQLException {
        // TODO Auto-generated method stub
        //需要根据从数据库中拿到的枚举的状态码返回一个枚举对象
        int code = rs.getInt(columnName);
        System.out.println("从数据库中获取的状态码:"+code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

    @Override
    public EmpStatus getResult(ResultSet rs, int columnIndex)
            throws SQLException {
        // TODO Auto-generated method stub
        int code = rs.getInt(columnIndex);
        System.out.println("从数据库中获取的状态码:"+code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

    @Override
    public EmpStatus getResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        // TODO Auto-generated method stub
        int code = cs.getInt(columnIndex);
        System.out.println("从数据库中获取的状态码:"+code);
        EmpStatus status = EmpStatus.getEmpStatusByCode(code);
        return status;
    }

}

EmpSatus.java

package com.gong.mybatis.bean;

public enum EmpStatus {
    LOGIN(100,"用户登录"),LOGOUT(200,"用户登出"),REMOVE(300,"用户不存在");
    private Integer code;
    private String msg;
    private EmpStatus(Integer code,String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public static EmpStatus getEmpStatusByCode(int code) {
        // TODO Auto-generated method stub
        switch(code){
        case 100:
            return LOGIN;
        case 200:
            return LOGOUT;
        case 300:
            return REMOVE;
        default:        
            return LOGOUT;
        }
    }
}

Employee.java

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private EmpStatus empStatus=EmpStatus.LOGOUT;
    Department dept;

测试:

package com.gong.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gong.mybatis.bean.Department;
import com.gong.mybatis.bean.Employee;
import com.gong.mybatis.dao.EmployeeMapper;
import com.gong.mybatis.mapper.EmployeeMapperDynamicSql;

public class TestMybatis5 {
    
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(is);
    }

    @Test
    public void test() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            //第一个参数为当前页码,第二个参数是每页的记录数
            Page<Object> page = PageHelper.startPage(1,2);
            List<Employee> emps = mapper.getAllEmp();
            //第一个参数为传入的数据,第二个参数为连续显示多少页
            PageInfo<Employee> pageInfo = new PageInfo<>(emps,3);
            for(Employee emp:emps) {
                System.out.println(emp);
            }
//            System.out.println("当前页码:"+page.getPageNum());
//            System.out.println("总记录数:"+page.getTotal());
//            System.out.println("每页几条记录:"+page.getPageSize());
//            System.out.println("总页码数:"+page.getPages());
            System.out.println("当前页码:"+pageInfo.getPageNum());
            System.out.println("总记录数:"+pageInfo.getTotal());
            System.out.println("每页几条记录:"+pageInfo.getPageSize());
            System.out.println("总页码数:"+pageInfo.getPages());
            System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
            System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
            System.out.println("连续显示的页码:");
            int[] navigatepageNums = pageInfo.getNavigatepageNums();
            for (int i = 0; i < navigatepageNums.length; i++) {
                System.out.println(navigatepageNums[i]);
            }
        } finally {
            // TODO: handle finally clause
            openSession.close();
        }
    }
    
    @Test
    public void testEnum() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Employee employee = new Employee();
            employee.setLastName("bom");
            employee.setGender("1");
            employee.setEmail("bom@qq.com");
            mapper.addEmp(employee);
            System.out.println("保存成功:"+employee.getId());
            openSession.commit();
        } finally {
            // TODO: handle finally clause
            openSession.close();
        }        
    }
}

结果:

DEBUG 01-23 16:02:56,976 ==>  Preparing: insert into tbl_employee(last_name,gender,email,empStatus) values(?,?,?,?)   (BaseJdbcLogger.java:145) 
要保存的状态码:200
DEBUG 01-23 16:02:57,030 ==> Parameters: bom(String), 1(String), bom@qq.com(String), 200(String)  (BaseJdbcLogger.java:145) 
DEBUG 01-23 16:02:57,046 <==    Updates: 1  (BaseJdbcLogger.java:145) 
保存成功:11

数据库中:

技术图片

 

存储的是自己定义的枚举类型中的code。

再进行查询:

            Employee employee = mapper.getEmpById(11);
            System.out.println(employee);
            System.out.println(employee.getEmpstatus());
            openSession.commit();

输出:

DEBUG 01-23 16:11:09,121 ==>  Preparing: select id,last_name lastName,email,gender,empStatus from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 01-23 16:11:09,180 ==> Parameters: 11(Integer)  (BaseJdbcLogger.java:145) 
从数据库中获取的状态码:200
DEBUG 01-23 16:11:09,237 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee [id=11, lastName=bom, gender=1, email=bom@qq.com, dept=null]
LOGOUT

说明确实是定义成功的。

同时,

        <!--2、也可以在处理某个字段的时候告诉MyBatis用什么类型处理器
                保存:#{empStatus,typeHandler=xxxx}
                查询:
                    <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmp">
                         <id column="id" property="id"/>
                         <result column="empStatus" property="empStatus" typeHandler=""/>
                     </resultMap>
                注意:如果在参数位置修改TypeHandler,应该保证保存数据和查询数据用的TypeHandler是一样的。
          -->

mybatis扩展之自定义类型处理器处理枚举类型

标签:object   map   exce   public   ltm   rate   for   span   resultmap   

原文地址:https://www.cnblogs.com/xiximayou/p/12230771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!