表关系: 问题表 1==>n 问题选项表,
需求: 查询问题时候,联查出来问题选项

//问题 实体类
public class Question {
private String id; //ID
private String content; //问题
private String type; //问题类型 1:单选,2:多选,3:问答
private Integer sort; //排序
private List<QuestionOption> options; //问题选项 *** 问题表里不需要有这个属性对应的字段
//...
}
1
2
3
4
5
6
7
8
9
//问题选项 实体类
public class QuestionOption{
private String id; //ID
private String qid; //问题ID *** 问题选项表里需要有这个属性对应的字段
private String content; //选项
private Integer sort; //排序
//...
}
1
2
3
4
5
6
7
8
方式一:
代码复用性高, 主表分页查询正确
1
QuestionMapper.xml

<mapper namespace="com.xxx.modules.xxx.mapper.QuestionMapper">

<resultMap -->
</resultMap>

<!-- 查询列表 -->
<select >
SELECT
pq.id, pq.content, pq.type, pq.sort
FROM
question AS pq
<where>
</where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
QuestionOptionMapper.xml

<mapper namespace="com.xxx.modules.xxx.mapper.QuestionOptionMapper">

<!-- 查询列表 -->
<select ,只要类型匹配,在这里随便写个变量名就可以取到值 #{xyz} -->
</where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
方式二:
只需要执行一次sql查询, 主表分页查询不正确
1
QuestionMapper.xml

<mapper namespace="com.xxx.modules.xxx.mapper.QuestionMapper">

<resultMap />
</collection>
<!-- 列的别名 o_id,o_content,o_sort , 起别名是因为主子表都有这几个字段
这里要写 ofType, javaType还是可以不写 -->
</resultMap>

<!-- 查询列表 -->
<select >
SELECT
pq.id, pq.content, pq.type, pq.sort
,pqo.id AS oid ,pqo.content AS ocontent ,pqo.sort AS osort <!-- 联查子表字段,起别名 -->
FROM
question AS pq
LEFT JOIN question_option pqo ON pq.id = pqo.qid <!-- 联查子表 -->
<where>
</where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
注意: 主子表要查询出来的字段名重复,要起别名
参考博客
————————————————
版权声明:本文为CSDN博主「lzxomg」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lzxomg/article/details/89739651

相关文章: