当我们在分页查询时,想把一条试卷数据的题目及日志信息读取出来,用到了mybatis mapper 中的collection 嵌套查询方法,
如下:
<resultMap id="shijuanBean" type="com.example.demo.shijuan.beans.ShijuanBean">
<result property="id" jdbcType="INTEGER" column="id"/>
<result property="shijuanid" jdbcType="VARCHAR" column="shijuanid"/>
<result property="lx" jdbcType="VARCHAR" column="lx"/>
<result property="zy" jdbcType="VARCHAR" column="zy"/>
<result property="zt" jdbcType="VARCHAR" column="zt"/>
<result property="name" jdbcType="VARCHAR" column="name"/>
<result property="the" jdbcType="VARCHAR" column="the"/>
<result property="uid" jdbcType="VARCHAR" column="uid"/>
<result property="uname" jdbcType="VARCHAR" column="uname"/>
<result property="ctime" jdbcType="VARCHAR" column="ctime"/>
<result property="bz" jdbcType="VARCHAR" column="bz"/>
<!--试题列表 -->
<collection property="tkList" select="searchShijuanTk" column="{shijuanid=shijuanid}" ofType="com.example.demo.tkgl.beans.TkBean"></collection>
<!--试题类型列表 -->
<collection property="tkTypeList" select="searchShijuanTkType" column="{shijuanid=shijuanid}" ofType="com.example.demo.tkgl.beans.TkBean"></collection>
<!--试题日志列表 -->
<collection property="tklogList" select="getShijuanListLog" column="{shijuanid=shijuanid}" ofType="com.example.demo.tkgl.beans.TkLogBean"></collection>
</resultMap>
那么访怎么写,还要注意什么问题呢?
一、mybatis mapper 进行一对多的查询时,我们需要在pojo类开中定义一个list
public class ShijuanBean extends PageBean {
private int id;
private String shijuanid;
private String lx;//类型
private String zy;//专业
private String zt;//状态
private String name;//名称
private String the;
private String uid;
private String uname;
private String ctime;//发布时间
private String bz;//备注
private String cz;//操作
private List<TkBean> tkList;//试题列表
private List<TkBean> tkTypeList;//试题类型列表
private List<TkLogBean> tklogList;//试题日志列表
private String total;//总分
private String fs;//组卷方式
二、mybatis mapper 语法
collection:集合元素
property::ShijuanBean中的list 属性名,
select:关联的sql,
column="{shijuanid=shijuanid}" 传递的查询条件,如果有多个,则是{shijuanid=shijuanid,shijuanid=shijuanid,shijuanid=shijuanid,shijuanid=shijuanid******}
ofType="com.example.demo.tkgl.beans.TkBean" 返回的类型是什么,集合属性的泛型类型 可为基本类型
三、注意的事项,页面显示的时候,如果不在application.xml中配置一个东西的话,那肯定会报错。当在controller 返回json的时候,因为是嵌套了list 对象,无法进行转换。
异常:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class com.google.common.cache.CacheStats and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
需要关闭spring boot 的FAIL_ON_EMPTY_BEANS
所以在spring boot application.xml文件中加上以下一个配置就可以了。
#延时加载 忽略无法转换的对象 spring.jackson.serialization.fail-on-empty-beans=false

本文介绍使用MyBatis进行一对多查询的方法,通过配置mapper文件实现试卷数据及其相关题目和日志信息的嵌套查询,并解决JSON序列化时出现的问题。
2337

被折叠的 条评论
为什么被折叠?



