myibatis3 使用 typeHandler自定义类型转换器

1. 使用myibatis3 时,把list 列表中的内容存储到数据库的 varchar 字段中。

2.pojo 类

public class Role implements Serializable {

    private Long id; //编号

    private String role; //角色标识

    private String description; //角色描述

    private List<Long> resourceIds; //拥有的资源(要转换的字段)

    private Boolean available = Boolean.FALSE; //是否可用

    public Role() {

    }

    public Role(String role, String description, Boolean available) {

        this.role = role;

        this.description = description;

        this.available = available;

    }

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getRole() {

        return role;

    }

    public void setRole(String role) {

        this.role = role;

    }

    public String getDescription() {

        return description;

    }

    public void setDescription(String description) {

        this.description = description;

    }

    public List<Long> getResourceIds() {

        if(resourceIds == null) {

            resourceIds = new ArrayList<Long>();

        }

        return resourceIds;

    }

    public void setResourceIds(List<Long> resourceIds) {

        this.resourceIds = resourceIds;

    }

    public String getResourceIdsStr() {

        if(CollectionUtils.isEmpty(resourceIds)) {

            return "";

        }

        StringBuilder s = new StringBuilder();

        for(Long resourceId : resourceIds) {

            s.append(resourceId);

            s.append(",");

        }

        return s.toString();

    }

    public void setResourceIdsStr(String resourceIdsStr) {

        if(StringUtils.isEmpty(resourceIdsStr)) {

            return;

        }

        String[] resourceIdStrs = resourceIdsStr.split(",");

        for(String resourceIdStr : resourceIdStrs) {

            if(StringUtils.isEmpty(resourceIdStr)) {

                continue;

            }

            getResourceIds().add(Long.valueOf(resourceIdStr));

        }

    }

    public Boolean getAvailable() {

        return available;

    }

    public void setAvailable(Boolean available) {

        this.available = available;

    }

    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Role role = (Role) o;

        if (id != null ? !id.equals(role.id) : role.id != null) return false;

        return true;

    }

    @Override

    public int hashCode() {

        return id != null ? id.hashCode() : 0;

    }

    @Override

    public String toString() {

        return "Role{" +

                "id=" + id +

                ", role='" + role + '\'' +

                ", description='" + description + '\'' +

                ", resourceIds=" + resourceIds +

                ", available=" + available +

                '}';

    }

}

3.定义类型转换类

import java.sql.CallableStatement;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import org.apache.ibatis.type.JdbcType;

import org.apache.ibatis.type.TypeHandler;

/**

 * list 列表存储到数据库时,存储为varchar 类型

 * 

 * @author dell

 *

 */

public class ListTypeHandler implements TypeHandler{

@Override

public Object getResult(ResultSet rs, String name) throws SQLException {

String value = rs.getString(name);

String [] array =value.split(",");

List<Long> list = new ArrayList<Long>();

if(null !=array){

int len = array.length;

for(int i=0;i<len;i++){

list.add(Long.parseLong(array[i]));

}

}

return list;

}

@Override

public Object getResult(ResultSet res, int in) throws SQLException {

return null;

}

@Override

public Object getResult(CallableStatement cst, int in) throws SQLException {

List<Long> list = (List<Long>)cst.getObject(in);

return list;

}

/**

*PreparedStatement pst, 

* int place, 参数位置

* Object obj, Java类型的对象

* JdbcType type  数据库类型

*/

@Override

public void setParameter(PreparedStatement pst, int place, Object obj, JdbcType type) throws SQLException {

@SuppressWarnings("unchecked")

List<Long> b = (List<Long>) obj;    

  StringBuffer value = new StringBuffer(60);

  for(Long l:b){

  value.append(l.toString()).append(",");

  }

  pst.setString(place, value.toString());

}

}

4.注册类型转化类

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<!-- 别名 -->

<typeAliases>

<typeAlias type="boce.auth.shiro.pojo.User" alias="user"/>

<typeAlias type="boce.auth.shiro.pojo.Resources" alias="Resources"/>

<typeAlias type="boce.auth.shiro.pojo.Role" alias="Role"/>

</typeAliases> 

<typeHandlers>

<typeHandler javaType="java.util.List" jdbcType="VARCHAR"    

      handler="boce.auth.common.util.ListTypeHandler" />

    </typeHandlers>

</configuration>

5. 使用自定义转化类

<?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="boce.auth.shiro.pojo.Role">

<resultMap type="Role" id="id_role">

<id column="id" property="id" />

<result column="role" property="role" />

<result column="description" property="description"/>

    <result column="resource_ids" property="resourceIds" javaType="java.util.List" jdbcType="VARCHAR"/>

  <result column="available" property="available" />

</resultMap> 

<insert id="id_insert_save" parameterType="Role" >

<selectKey keyProperty="id" order="BEFORE" resultType="Long">

select sql_id.nextval from dual

</selectKey>

insert into sys_role(id, role, description, 

resource_ids, available) 

values

     (#{id}, #{role,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, 

     #{resourceIds,javaType=java.util.List,jdbcType=VARCHAR}, 

     #{available})

</insert>

</mapper>

6.表结构:

create table SYS_ROLE

(

  ID           NUMBER not null,

  ROLE         VARCHAR2(100),

  DESCRIPTION  VARCHAR2(100),

  RESOURCE_IDS VARCHAR2(100),

  AVAILABLE    INTEGER default 0

);



 

测试结果:



 

猜你喜欢

转载自gjp014.iteye.com/blog/2300615
今日推荐