mybatis 自定义传入参数类型(TypeHandler)
mybatis 自定义传入参数类型(TypeHandler)
关于处理model中list属性,要将list中的值转化为string存储到数据库中, java:List 数据库:varchar
Model中的属性是
private List
Mysql数据库存储为:varchar(2000)
在自定义的typeHandler中定义方法
public class ListTypeHandler implements TypeHandler<List
@Override
public List<ProtectedBO> getResult(ResultSet rs, String column) throws SQLException {
String protectedListValue = rs.getString(column);
return protectedListValue == null ? null
: new Gson().fromJson(protectedListValue, new TypeToken<List<ProtectedBO>>() {
}.getType());
}
@Override
public List<ProtectedBO> getResult(ResultSet rs, int index) throws SQLException {
String protectedListValue = rs.getString(index);
return protectedListValue == null ? null
: new Gson().fromJson(protectedListValue, new TypeToken<List<ProtectedBO>>() {
}.getType());
}
@Override
public List<ProtectedBO> getResult(CallableStatement cs, int index) throws SQLException {
String protectedListValue = cs.getString(index);
return protectedListValue == null ? null
: new Gson().fromJson(protectedListValue, new TypeToken<List<ProtectedBO>>() {
}.getType());
}
@Override
public void setParameter(PreparedStatement ps, int index, List<ProtectedBO> protectedList, JdbcType jdbcType)
throws SQLException {
if (null == protectedList || protectedList.size() == 0 || protectedList.isEmpty()) {
ps.setNull(index, Types.VARCHAR);
} else {
ps.setString(index, new Gson().toJson(protectedList));
}
}
mybatis mapper.xml的添加或者编辑方法
mybatis-config.xml中加入如下的代码声明自定义handler