Mybatis查询数据部分字段显示为null,怎么转成空串("")

Mybatis查询数据部分字段显示为null,怎么转成空串("")

1、先定义一个handler,来把字段为null的转成空串("")
2、在Mapper.xml中,把可能为空的字段,加上typeHandler属性,指定处理的handler类的全路径。

CustomStringTypeHandler.java

package com.wang.common.mybatis.handler;

import org.apache.ibatis.executor.result.ResultMapException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

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

/**
 * @Name: CustomStringTypeHandler
 * @Desc: 自定义mybatis处理类,将null返回为空串(‘’)
 * @Author: Administrator
 * @Date: 2019-09-03 18:20
 */
@MappedTypes({String.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class CustomStringTypeHandler extends BaseTypeHandler {


    @Override
    public String getResult(ResultSet rs, String columnName) {
        String result;
        try {
            result = getNullableResult(rs, columnName);
        } catch (Exception e) {
            throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
        }
        return result;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getString(columnName) == null? "" : rs.getString(columnName);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getString(columnIndex) == null? "" : rs.getString(columnIndex);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getString(columnIndex) == null? "" : cs.getString(columnIndex);
    }
}

Mapper.xml




  
    
    
    
    
    
    
    
    
    
    
    
  
  

没有加typeHandler属性,处理之前的查询结果:

BusinessTrip(requestId=11925, jobNumber=5721, requestDate=2019-05-06, department=57, businessDays=21, cfd=上海, mdd=南京, startTime=2019-05-06 13:36, endTime=2019-05-07 13:36, reason=null, remark=null)

增加typeHandler属性,处理后的结果:(reason和remark字段都变成了空串)

BusinessTrip(requestId=11925, jobNumber=5721, requestDate=2019-05-06, department=57, businessDays=21, cfd=上海, mdd=南京, startTime=2019-05-06 13:36, endTime=2019-05-07 13:36, reason=, remark=)

你可能感兴趣的:(Mybatis)