mybatis枚举自动转换实现

来源:互联网 发布:淘宝无线端营销 编辑:程序博客网 时间:2024/06/03 12:44

原文链接:http://blog.csdn.net/fighterandknight/article/details/51520402

原文的第二篇文章写了如何处理通用转换的问题,因为我没亲自尝试过,就不写了。

前言

           在设计数据库的时候,我们有时候会把表里的某个字段的值设置为数字或者为英文来表示他的一些特殊含义。就拿设置成数字来说,假如1对应是学生,2对应是教师,在Java里面定义成这样的枚举,但是一般使用mybatis查出来的话,我们想要让它自动装换成我们想要的枚举,不需要再手动根据数值去判断设置成我们想要的枚举。要是实现这样的效果,那么我们就要用到mybatis的BaseTypeHandler了。

           

BaseTypeHandler介绍

             让我们来看看要继承BaseTypeHandler这个抽象类,需要覆写哪些方法:

[java] view plain copy
  1. public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;  
  2.   
  3. public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;  
  4.   
  5. public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;  
  6.   
  7. public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;  

实现了这些抽象类,当得到结果集的时候,程序就会回调这些方法,例如根据名称获取当前行的某一列的值,那么就会直接回调getNullableResult(ResultSet rs, String columnName)这个方法,根据名称得到当行的当前列的值,然后我们在这里去调用枚举,匹配枚举中的每一个值,相等的话直接返回该枚举,达到自动转换成我们想要的枚举的效果。其他的重载方法类似,只不过是有些根据列索引,有些根据列名称做枚举自动转换而已。

好了,介绍就到这里,让我们来看看具体实现。。



自动转换实现例子

创建数据库表



创建枚举

[java] view plain copy
  1. package net.itaem.less;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. /** 
  7.  * @author: Fighter168 
  8.  */  
  9. public enum PersonType{   
  10.     STUDENT("1","学生"),  
  11.     TEACHER("2","教师");  
  12.       
  13.     private String value;  
  14.     private String displayName;  
  15.       
  16.     static Map<String,PersonType> enumMap=new HashMap<String, PersonType>();  
  17.     static{  
  18.         for(PersonType type:PersonType.values()){  
  19.             enumMap.put(type.getValue(), type);  
  20.         }  
  21.     }  
  22.       
  23.     private PersonType(String value,String displayName) {  
  24.          this.value=value;  
  25.          this.displayName=displayName;  
  26.     }  
  27.       
  28.     public String getValue() {  
  29.         return value;  
  30.     }  
  31.     public void setValue(String value) {  
  32.         this.value = value;  
  33.     }  
  34.     public String getDisplayName() {  
  35.         return displayName;  
  36.     }  
  37.     public void setDisplayName(String displayName) {  
  38.         this.displayName = displayName;  
  39.     }  
  40.       
  41.     public static PersonType getEnum(String value) {  
  42.         return enumMap.get(value);  
  43.     }  
  44. }  




创建Po实体类

[java] view plain copy
  1. /** 
  2.  * @author: Fighter168 
  3.  */  
  4. public class Person {  
  5.     private String id;  
  6.     private String name;  
  7.     //枚举  
  8.     private PersonType personType;  
  9.         //set get 方法。。  
  10. }  


创建Dao接口

创建一个简单的测试dao,这里简单的提供一个测试的查询方法。

[java] view plain copy
  1. /** 
  2.  * @author: Fighter168 
  3.  */  
  4. public interface PersonDao {  
  5.   
  6.     public List<Person> query();  
  7.   
  8. }  

创建枚举转换处理器

[java] view plain copy
  1. package net.itaem.handler;  
  2.   
  3. import java.sql.CallableStatement;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7.   
  8. import net.itaem.less.PersonType;  
  9.   
  10. import org.apache.ibatis.type.BaseTypeHandler;  
  11. import org.apache.ibatis.type.JdbcType;  
  12.   
  13. /** 
  14.  * @author: Fighter168 
  15.  */  
  16. public class PersonTypeHandler extends BaseTypeHandler<PersonType>{  
  17.   
  18.     private Class<PersonType> type;  
  19.   
  20.     private  PersonType[] enums;  
  21.       
  22.     /** 
  23.      * 设置配置文件设置的转换类以及枚举类内容,供其他方法更便捷高效的实现 
  24.      * @param type 配置文件中设置的转换类 
  25.      */  
  26.     public PersonTypeHandler(Class<PersonType> type) {  
  27.         if (type == null)  
  28.             throw new IllegalArgumentException("Type argument cannot be null");  
  29.         this.type = type;  
  30.         this.enums = type.getEnumConstants();  
  31.         if (this.enums == null)  
  32.             throw new IllegalArgumentException(type.getSimpleName()  
  33.                     + " does not represent an enum type.");  
  34.     }  
  35.   
  36.     @Override  
  37.     public PersonType getNullableResult(ResultSet rs, String columnName) throws SQLException {  
  38.         // 根据数据库存储类型决定获取类型,本例子中数据库中存放String类型  
  39.         String i = rs.getString(columnName);  
  40.         if (rs.wasNull()) {  
  41.             return null;  
  42.         } else {  
  43.             // 根据数据库中的value值,定位PersonType子类  
  44.             return PersonType.getEnum(i);  
  45.         }  
  46.     }  
  47.   
  48.     @Override  
  49.     public PersonType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {  
  50.         // 根据数据库存储类型决定获取类型,本例子中数据库中存放String类型  
  51.          String i = rs.getString(columnIndex);  
  52.         if (rs.wasNull()) {  
  53.             return null;  
  54.         } else {  
  55.              // 根据数据库中的value值,定位PersonType子类  
  56.             return PersonType.getEnum(i);  
  57.         }  
  58.     }  
  59.   
  60.     @Override  
  61.     public PersonType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {  
  62.          // 根据数据库存储类型决定获取类型,本例子中数据库中存放String类型  
  63.      String i = cs.getString(columnIndex);  
  64.        if (cs.wasNull()) {  
  65.            return null;  
  66.        } else {  
  67.          // 根据数据库中的value值,定位PersonType子类  
  68.            return PersonType.getEnum(i);  
  69.        }  
  70.     }  
  71.   
  72.     @Override  
  73.     public void setNonNullParameter(PreparedStatement ps, int i, PersonType parameter, JdbcType jdbcType)  
  74.             throws SQLException {  
  75.         // baseTypeHandler已经帮我们做了parameter的null判断  
  76.         ps.setString(i, parameter.getValue());  
  77.   
  78.     }  
  79.       
  80. }  



创建Mapper映射文件

PersonDao对应的PersonMapper映射文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="net.itaem.dao.PersonDao" >  
  4.     
  5.   <resultMap id="resultMap" type="net.itaem.po.Person" >  
  6.         <result column="id" property="id" jdbcType="CHAR" />  
  7.         <result column="name" property="name" jdbcType="CHAR" />  
  8.         <result column="type" property="personType" jdbcType="CHAR" />  
  9.   </resultMap>  
  10.    
  11.  <select id="query"  resultMap="resultMap">  
  12.     select * from person  
  13.  </select>  
  14.     
  15. </mapper>  
其实handler还可以写在PersonMapper.xml这里,写成下面这样:

[html] view plain copy
  1. <result column="type" property="personType"  typeHandler="net.itaem.handler.PersonTypeHandler"/>  





创建Spring的配置文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  5.      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">   
  6.          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>  
  7.          <property name="url" value="jdbc:mysql://localhost:3306/test"/>  
  8.          <property name="username" value="root"/>  
  9.          <property name="password" value="123abc"/>  
  10.          <!-- 连接池启动时候的初始连接数 -->  
  11.          <property name="initialSize" value="10"/>  
  12.          <!-- 最小空闲值 -->  
  13.          <property name="minIdle" value="5"/>  
  14.          <!-- 最大空闲值 -->  
  15.          <property name="maxIdle" value="20"/>  
  16.          <property name="maxWait" value="2000"/>  
  17.          <!-- 连接池最大值 -->  
  18.          <property name="maxActive" value="50"/>  
  19.          <property name="logAbandoned" value="true"/>  
  20.          <property name="removeAbandoned" value="true"/>  
  21.          <property name="removeAbandonedTimeout" value="180"/>  
  22.     </bean>  
  23.       
  24.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  25.         <property name="configLocation" value="classpath:/resource/cfg.xml"/>  
  26.         <property name="dataSource" ref="dataSource"/>  
  27.     </bean>  
  28.    
  29.      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  30.          <property name="basePackage" value="net.itaem.dao"/>   
  31.      </bean>  
  32. </beans>  

创建mybatis的配置文件

下面是为mybatis创建配置文件cfg.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2. <!DOCTYPE configuration    
  3.   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"    
  4.   "http://mybatis.org/dtd/mybatis-3-config.dtd">    
  5. <configuration>    
  6.     <typeHandlers>  
  7.      <typeHandler handler="net.itaem.handler.PersonTypeHandler"  
  8.          javaType="net.itaem.less.PersonType" jdbcType="CHAR"/>  
  9.     </typeHandlers>  
  10.     <!-- mapping 文件路径配置 -->    
  11.     <mappers>    
  12.         <mapper resource="resource/PersonMapper.xml" />    
  13.     </mappers>    
  14. </configuration>  

创建测试用例

[java] view plain copy
  1. /** 
  2.  * @author: Fighter168 
  3.  */  
  4. public class SpringTest {  
  5.   
  6.     public static void main(String[] args) {  
  7.         ApplicationContext context=new ClassPathXmlApplicationContext("resource/ApplicationContext.xml");  
  8.         PersonDao personDao=(PersonDao) context.getBean("personDao");  
  9.         List<Person> list=personDao.query();  
  10.         for(Person p:list){  
  11.             System.out.println(p.toString());  
  12.         }  
  13.     }  
  14. }  

测试结果展示

结果是成功自动转换成了我们想要的枚举




万能枚举转换处理器?

             也许我们还在想,如果我们有几十个枚举,这样转换的话,那我们岂不是要分别为每一个枚举定义一个Handler,然后为每一个Handler注册。其实不必这样,我们可以定义成一个通用的枚举转换处理器,具体怎么实现呢,下一篇博客我会告诉大家   mybatis枚举自动转换(通用转换处理器实现)


原创粉丝点击