利用MyBatis中typeHandlers属性将List数据存储到数据库中

在mybatis框架中,可以利用设置typeHandlers属性来实现数据库的数据与java类型的转换,一般由系统提供,但若是一些特殊的例如数组、集合的数据,那么我们需要自定义我们自己的类型转换器, 将list集合存储到数据库中:我们就需要在查询语句中,将List转换成字符串的形式设置到占位符中,同样从数据库中取可以将取到的字符串的数据转换成List集合,下面是代码演示:

1.定义的pojo类

package com.sb.pojo;

import java.util.List;

public class Dept {
     
	private Integer deptno;
	private String dname;
	private String loc;
	private List<String> country;
	
	public Dept() {
     
		super();
	}

	@Override
	public String toString() {
     
		return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + ", country=" + country + "]";
	}

	public Dept(Integer deptno, String dname, String loc, List<String> country) {
     
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
		this.country = country;
	}

	public Integer getDeptno() {
     
		return deptno;
	}

	public void setDeptno(Integer deptno) {
     
		this.deptno = deptno;
	}

	public String getDname() {
     
		return dname;
	}

	public void setDname(String dname) {
     
		this.dname = dname;
	}

	public String getLoc() {
     
		return loc;
	}

	public void setLoc(String loc) {
     
		this.loc = loc;
	}

	public List<String> getCountry() {
     
		return country;
	}

	public void setCountry(List<String> country) {
     
		this.country = country;
	}	
}

2.自定义类型转换器

package com.sb.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class StrToVarcharTypeHandler extends BaseTypeHandler<List<String>>{
     
	/**
	 * 处理到数据库的参数,将list属性以字符串的形式设置到sql语句的占位符中
	 */
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
			throws SQLException {
     
		StringBuilder sb = new StringBuilder();
		for (String string : parameter) {
     
			sb.append(string);
			//各参数以";"分割,以便取数据时可以分隔这个
			sb.append(";");
		}
		//将字符串的最后一个分号去掉
		String result = sb.toString().substring(0, sb.length()-1);
		//设置占位符
		ps.setString(i, result);
		
	}
	/**
	 * 从数据库中返回数据,将varchar字符串分隔,并以list的形式返回
	 */
	@Override
	public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
     
		if (rs.getString(columnName) !=null) {
     
			return Arrays.asList(rs.getString(columnName).split(";"));			
		}
		return null;
	}

	@Override
	public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
     
		if (rs.getString(columnIndex) !=null) {
     
			return Arrays.asList(rs.getString(columnIndex).split(";"));			
		}
		return null;
	}

	@Override
	public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
     
		if (cs.getString(columnIndex) !=null) {
     
			return Arrays.asList(cs.getString(columnIndex).split(";"));			
		}
		return null;
	}
}

3.在全局配置文件中配置typeHandlers标签:注意书写顺序



<configuration>

 <properties resource="db.properties">properties>
 
 <typeAliases>
 	<typeAlias type="com.sb.pojo.Dept" alias="Dept"/>
 typeAliases> 
 <typeHandlers>
	<typeHandler handler="com.sb.typehandler.StrToVarcharTypeHandler"/>  
  typeHandlers>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driverName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      dataSource>
    environment>
  environments>
  
  <mappers>
  
  
  
  <package name="com.sb.dao"/>
  mappers>
  
configuration>

4.映射xml文件

<insert id="insert" parameterType="dept">
	 insert into dept(deptno,dname,loc,country) values(#{
     deptno},#{
     dname},#{
     loc},#{
     country})
</insert>

5.测试及结果

1.添加测试
public class Test {
     

	public static void main(String[] args) throws IOException {
     
		SqlSessionFactory ss = DbUtil.getSqlSession();
		SqlSession session = ss.openSession(true);
		IDeptDao mapper = session.getMapper(IDeptDao.class);
		List<String> list =new ArrayList<>();
		list.add("China");
		list.add("America");
		list.add("Japan");
		mapper.insert(new Dept(55, "sale", "TaT", list));
	}

}
2.查询测试
public class Test {
     

	public static void main(String[] args) throws IOException {
     
		SqlSessionFactory ss = DbUtil.getSqlSession();
		SqlSession session = ss.openSession(true);
		IDeptDao mapper = session.getMapper(IDeptDao.class);
		List<Dept> query = mapper.query();
		for (Dept dept : query) {
     
			System.out.println(dept);
		}
	}

}

插入数据结果:
在这里插入图片描述
查询数据结果:
利用MyBatis中typeHandlers属性将List数据存储到数据库中_第1张图片

你可能感兴趣的:(mybatis,mybatis)