Mybatis 返回数组 两种方式
mysql没有数组这种类型,我们可以以数组格式的字符串加入到数据库,返回值是数组1.Mapper.xml 返回数组<resultMap type="返回实体类" id="result" ><result property="实体类字段名" column="mysql字段名" typeHandler="处理数据的文件"/></resultMap><selec
·
mysql没有数组这种类型,我们可以以数组格式的字符串加入到数据库,返回值是数组
1.Mapper.xml 返回数组
<resultMap type="返回实体类" id="result" >
<result property="实体类字段名" column="mysql字段名" typeHandler="处理类"/>
</resultMap>
<select id="Mapper.java的方法名" parameterType="传参类型" resultMap="resultMap的id">
select pricture from xm_picture
</select>
例如:
<resultMap type="co.yixiang.modules.service.dto.PictureDto" id="PictureResult" >
<result property="pictureArr" column="picture" typeHandler="co.yixiang.utils.mybatis.JsonStringArrayTypeHandler"/>
</resultMap>
<!-- parameterType 也可以是实体类 -->
<select id="selectPictureById" parameterType="Long" resultMap="PictureResult">
select pricture from xm_picture where id = #{id}
</select>
2.Mapper.java 返回数组 @Select注解
@Select("<script>" +
" select picture from xm_picture where id = #{id} " +
"</script>")
@Results({@Result(property="实体类字段名",column="数据库字段名",typeHandler= 处理类.class)})
PictureDto selectById(Long id);
例如
@Select("<script>" +
" select picture from xm_picture where id = #{id} " +
"</script>")
@Results({@Result(property="pictureArr",column="picture",typeHandler= JsonStringArrayTypeHandler.class)})
PictureDto selectById(Long id);
处理类代码
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedJdbcTypes({JdbcType.VARCHAR})
public class JsonStringArrayTypeHandler extends BaseTypeHandler<String[]> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, toJson(parameter));
}
@Override
public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
return this.toObject(rs.getString(columnName));
}
@Override
public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return this.toObject(rs.getString(columnIndex));
}
@Override
public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return this.toObject(cs.getString(columnIndex));
}
private String toJson(String[] params) {
try {
return mapper.writeValueAsString(params);
} catch (Exception e) {
e.printStackTrace();
}
return "[]";
}
private String[] toObject(String content) {
if (content != null && !content.isEmpty()) {
try {
return (String[]) mapper.readValue(content, String[].class);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
}
更多推荐
所有评论(0)
您需要登录才能发言
加载更多