mybatis 返回null 轉 空字符串


package com.neusoft.mid.msf.issaweb.config;

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: zhou.wang

  • @Date: 2021-05-20 13:41
    */
    @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);
    }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM