1. resulttype和resultMap
当查询接口需要查询数据库时,通常我们会封装查询的数据库数据映射到实体类中,result type类型为自定义的实体类,当实体类的属性和数据库的字段不是一一对应时,就需要我们手动配置resultMap
2. resultMap简单使用
2.1 实体类
public class Class {
private Integer id;
private String classname;
}
2.2 数据库字段
可以看出数据库中的字段名为name,实体类的字段名为classname
2.3 controller层
@GetMapping("/findClass/{id}")
public Class test1(@PathVariable int id){
return resultMapDao.selectClass(id);
}
2.4 dao层
lass selectClass(int id);
2.5 mapper层
<select id="selectClass" parameterType="int" resultMap="TestMap">
select * from class where id=#{id}
</select>
<resultMap id="TestMap" type="com.example.demo.Class">
<id property="id" column="ID"/>
<result property="classname" column="name"/>
</resultMap>
结果
{
"id": 1,
"classname": "高一一班"
}
3. 使用resultMap进行关联查询
3.1 一对一查询
一个班级只能有一个班主任
3.1.1 实体类
班级类
public class Class {
private Integer id;
private String classname;
private Teacher teacher;
}
教师类
public class Teacher {
private Integer id;
private String teachername;
private Integer classid;
}
3.1.2 数据库字段
教师表
3.1.3 mapper 层
<select id="selectClass" parameterType="int" resultMap="TestMap">
select *
from class c
left join teacher t on t.classid = c.id
where c.id = #{id} </select>
<resultMap id="TestMap" type="com.example.demo.Class">
<id property="id" column="ID"/>
<result property="classname" column="name"/>
<association property="teacher" javaType="com.example.demo.Teacher" column="id">
<id property="id" column="ID"/>
<result property="teachername" column="tname"/>
<result property="classid" column="classid"/>
</association>
</resultMap>
3.1.4 查询结果
{
"id": 1,
"classname": "高一一班",
"teacher": {
"id": 1,
"teachername": "小王老师",
"classid": 1
}
}
3.2 一对多查询
一个班级有多个学生
3.2.1 修改实体类
班级类
public class Class {
private Integer id;
private String classname;
private List<Class> aclass;
}
学生类
public class Student {
private Integer id;
private String name;
private Integer classid;
}
3.2.2 修改mapper
<select id="selectClass" parameterType="int" resultMap="TestMap">
select *
from class c
left join student s on s.classid = c.id
where c.id = #{id} </select>
<resultMap id="TestMap" type="com.example.demo.Class">
<id property="id" column="ID"/>
<result property="classname" column="name"/>
<collection property="aclass" javaType="java.util.ArrayList" ofType="com.example.demo.Student">
<id property="id" column="sid"/>
<result property="name" column="cname"/>
<result property="classid" column="classid"/>
</collection>
</resultMap>
3.2.3 结果
{
"id": 1,
"classname": "高一一班",
"aclass": [
{
"id": 1,
"name": "刘翔",
"classid": 1
},
{
"id": 2,
"name": "苏炳添",
"classid": 1
}
]
}
|