您的位置:首页 > 数据库

对于sql字段非空但插入值为空,将值转换为空的字符串

2017-10-19 17:59 495 查看
第一步:实现mybatls中的接口TypeHandler,其中有四个方法

public String getResult(ResultSet arg0, String arg1) throws SQLException 

public String getResult(ResultSet arg0, int arg1) throws SQLException

public String getResult(CallableStatement arg0, int arg1) throws SQLException

public void setParameter(PreparedStatement arg0, int arg1, String arg2, JdbcType arg3) throws SQLException 

主要用第四个方法。

第二步:创建一个类实现这个接口

package com.rthd.controller.person;

import java.sql.CallableStatement;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;

import org.apache.ibatis.type.TypeHandler;

public class NullValueHandler implements TypeHandler<String> {

@Override
public String getResult(ResultSet arg0, String arg1) throws SQLException {
// TODO Auto-generated method stub
return arg0.getString(arg1);
}

@Override
public String getResult(ResultSet arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return arg0.getString(arg1);
}

@Override
public String getResult(CallableStatement arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return arg0.getString(arg1);
}

@Override
public void setParameter(PreparedStatement arg0, int arg1, String arg2, JdbcType arg3) throws SQLException {
if(arg2==null && arg3==JdbcType.VARCHAR){
arg0.setString(arg1, "");
}else{
arg0.setString(arg1, arg2);
}

}

}

第三步:在spring-mybatils配置文件中注入

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.rthd.bean"></property>
<!-- 插入为空的值是实现接口typeHandlers -->
<property name="typeHandlersPackage" value="com.rthd.controller.person"></property>

第四步:在sql语句中

#{dimiapport,jdbcType=VARCHAR,typeHandler=com.rthd.controller.person.NullValueHandler},

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: