题目对象 Subject
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Data
public class Subject implements Serializable {
/***
* @Fields serialVersionUID:序列化ID
*/
private static final long serialVersionUID = 1L;
/**主键*/
private Integer id;
/**分类id*/
private int catalogId;
/**题目*/
private String title;
/**题目类型(1单选 2多选 3判断*/
private String type;
/**题目类型文本*/
private String typeText;
/**正确答案(单选A 多选ABC 判断题true)*/
private String correctAnswer;
/**问题解析*/
private String analysis;
/**是否可用 0 不可用 1可用*/
private String isUsable;
/**创建时间*/
private Date createTime;
/**试题选项*/
private List<SubjectOption> options;
}
选项对象
import lombok.Data;
import java.io.Serializable;
@Data
public class SubjectOption implements Serializable {
/***
* @Fields serialVersionUID:序列化ID
*/
private static final long serialVersionUID = 1L;
/**主键*/
private Integer id;
/**题目id*/
private Integer subjectId;
/**选项(A、B、C)*/
private String optionKey;
/**选项描述*/
private String optionDesc;
/**排序(1、2、3)*/
private Integer orderby;
/**是否是正确选项*/
private Integer correct;
}
一个题目对应多个选项
SubjectDAO
public interface ISubjectDAO {
/**
* 根据分类id查询题目
* */
List<Subject> getSubjectByCatalogId(Integer catalogId);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="ISubjectDAO">
<resultMap id="SubjectDetail" type="Subject">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="correctAnswer" property="correctAnswer" jdbcType="VARCHAR"/>
<result column="title" property="title" jdbcType="VARCHAR"/>
<collection property="options"
column="id"
javaType="ArrayList"
ofType="SubjectOption"
select="selectOptionBySubjectId"/>
</resultMap>
<select id="selectOptionBySubjectId" resultType="SubjectOption" parameterType="Integer">
SELECT
id AS id,
subject_id AS subjectId,
option_key AS optionKey,
option_desc AS optionDesc,
orderby AS orderBy,
correct AS correct
FROM
ssk_subject_option
WHERE
subject_id = #{id}
</select>
<select id="getSubjectByCatalogId" resultMap="SubjectDetail" parameterType="integer">
select
correct_answer as correctAnswer,
id as id,
type as type
from
ssk_subject
where
catalog_id = #{catalogId}
</select>
</mapper>
查询的入口方法是 getSubjectByCatalogId,根据分类id查询题目,这里因为题目和选项的关系是一对多,如果直接left join选项表的话,查出来的数据数目是不对的,所以这里设置resultMap,用<collection>标签,property是Subject对象里面定义的选项数组,表示查出来选项之后会装到这个数组里面,select 表示查询选项的方法,colunm表示要传进select="selectOptionBySubjectId"方法内的参数,这里的话,是要把题目id传到selectOptionBySubjectId里面去查选项,getSubjectByCatalogId方法中查询出来的题目id变量名就是id,所以column传id,想传哪个变量进去,column就写哪个。
查出来是这样的: