Mybatis返回数组两种⽅式
mysql没有数组这种类型,我们可以以数组格式的字符串加⼊到数据库,返回值是数组
l 返回数组
<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="dules.service.dto.PictureDto" id="PictureResult" >
<result property="pictureArr" column="picture" typeHandler="co.batis.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.pe.BaseTypeHandler;
import org.pe.JdbcType;
import org.pe.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 {
String(columnName));
}
@Override
public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String(columnIndex));
}
@Override
public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String(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()) {
write的返回值
try {
return (String[]) adValue(content, String[].class);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。