首页 > 其他分享 >MyBatis-plus 新增时List转String 查询时String转list

MyBatis-plus 新增时List转String 查询时String转list

时间:2022-10-10 15:34:15浏览次数:46  
标签:java String List list result import

MyBatis-plus 新增时List转String 查询时String转list

1. 需求说明

项目为:SpringBoot+MyBatisPlus

采用实体类接受参数,有一个参数为List ,对应的数据库字段为nvachar,要求新增时将List序列化为String插入数据库中,查询时将String转成

List

2.具体操作

  1. 新增自定义的typeHandler,继承BaseTypeHandler,具体代码如下:
package com.zjjg.dlbp.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springblade.core.tool.utils.ObjectUtil;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * List<Integer> ==>  string
 * @Date 2022-10-08
 */
public class ListToStringHandle extends BaseTypeHandler<List> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        if (ObjectUtil.isNotEmpty(list)){
            preparedStatement.setString(i, JSON.toJSONString(list));
        }

    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return result ==null? new ArrayList<>():JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return result ==null? new ArrayList<>():JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return result ==null? new ArrayList<>():JSONArray.parseArray(result);
    }
}

  1. 在数据库对应实体类字段上增加注解

        @TableField(jdbcType = JdbcType.VARCHAR,typeHandler = ListToStringHandle.class)
        private List<Integer> protectiveFacility;
    
        @TableField(jdbcType = JdbcType.VARCHAR,typeHandler = ListToStringHandle.class)
        private List<Integer> drainageFacility;
    
  2. 在mapper.xml中 对应字段上添加typeHandler

     <result column="drainage_facility" property="drainageFacility" typeHandler="com.zjjg.dlbp.config.ListToStringHandle"/>
     <result column="protective_facility" property="protectiveFacility" typeHandler="com.zjjg.dlbp.config.ListToStringHandle"/>
    
  3. 在application.yml文件中,增加 type-handlers-package配置,设置typeHandle所在包位置

    mybatis-plus:
    	type-handlers-package: com.app.config
    

标签:java,String,List,list,result,import
From: https://www.cnblogs.com/XiaoMingStudy1/p/16775899.html

相关文章