自定义TypeHandler类
我写的这个类是根据项目需要写的!
应用场景:数据库的字段类型是int类型的,项目的字段类型是一个自定义对象类型的,需要进行类型转换!
1、创建一个handler类,继承BaseTypeHandler,话不多说,直接放码!
import com.yd.tech.read.entity.StateEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
public class StateToIntHandler extends BaseTypeHandler<StateEntity> {
private static final Log log = LogFactory.getLog(StateToIntHandler.class);
@Override
public void setNonNullParameter(PreparedStatement ps, int i, StateEntity parameter, JdbcType jdbcType) throws SQLException {
Integer aa = parameter.getState();
if (aa==1){
ps.setInt(i, 1);
}else if(aa==0){
ps.setInt(i, 0);
}
}
@Override
public StateEntity getNullableResult(ResultSet rs, String columnName) throws SQLException {
//获取数据库的值
int ss=rs.getInt(columnName);
StateEntity state0 = new StateEntity(0);
StateEntity state1 = new StateEntity(1);
if(ss==1){
return state1;
}else if(ss==0){
return state0;
}else{
return null;
}
}
@Override
public StateEntity getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
//获取数据库的值
int ss=rs.getInt(columnIndex);
StateEntity state0 = new StateEntity(0);
StateEntity state1 = new StateEntity(1);
if(ss==1){
return state1;
}else if(ss==0){
return state0;
}else{
return null;
}
}
@Override
public StateEntity getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
//获取数据库的值
int ss=cs.getInt(columnIndex);
StateEntity state0 = new StateEntity(0);
StateEntity state1 = new StateEntity(1);
if(ss==1){
return state1;
}else if(ss==0){
return state0;
}else{
return null;
}
}
}
2、配置mabtis-config.xml
<typeHandlers>
<typeHandler handler="com.tech.read.handler.StateToIntHandler"/>
</typeHandlers>
3、mapper.xml中应用
<resultMap id="DataResultMap" type="DataEntity">
<id column="data_id" property="dataId"/>
<result column="add_time" property="addTime"/>
<result column="update_time" property="updateTime"/>
<result column="state" property="state" typeHandler="com.yd.tech.read.handler.StateToIntHandler"/>
</resultMap>
<select id="queryAll" resultMap="DataResultMap">
select * from table
<include refid="order"/>
</select>