mybatis返回数组的两种方式
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;
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论