用ideal软件编写代码
mybatis
多表查询
下面展示利用结果集映射 实现一对一 代码
mapper文件
// An highlighted block
var foo = 'bar';
<!--一对一 结果集映射 包含学生 +教师-->
<resultMap id="BaseResultMap3" type="com.rj.entity.Students">
<id column="stu_id" property="stuId"></id>
<result column="stu_name" property="stuName"></result>
<result column="stu_age" property="stuAge"></result>
<result column="stu_gender" property="stuGender"></result>
<result column="tea_id" property="teaId"></result>
<result column="stu_create_date" property="stuCreateDate"></result>
<association property="teacher" javaType="com.rj.entity.Teacher">
<id column="t_id" property="tId"></id>
<result column="t_name" property="tName"></result>
<result column="t_profession" property="tProfession"></result>
</association>
</resultMap>
<!--查询学生教师表 一对一-->
<select id="selectone2one" resultMap="BaseResultMap3">
select s.*,t.* from students s,teacher t where s.tea_id=t_id
</select>
在实体类中添加 教师属性 并且实现getset tostring和有参无参构造
// A code block
var foo = 'bar';
private int stuId;
private String stuName;
private int stuAge;
private String stuGender;
private int teaId;
private Date stuCreateDate;
//添加教师属性
private Teacher teacher;
下面展示一些 利用结果集映射 实现一对多 代码
mapper文件
// An highlighted block
var foo = 'bar';
<!--一对多 结果集映射 包含学生 +课程-->
<resultMap id="BaseResultMap4" type="com.rj.entity.Students">
<id column="stu_id" property="stuId"></id>
<result column="stu_name" property="stuName"></result>
<result column="stu_age" property="stuAge"></result>
<result column="stu_gender" property="stuGender"></result>
<result column="tea_id" property="teaId"></result>
<result column="stu_create_date" property="stuCreateDate"></result>
<collection property="subjects" ofType="com.rj.entity.Subject">
<id column="sub_id" property="subId"></id>
<result column="sub_name" property="subName"></result>
<result column="stu_id" property="stuId"></result>
</collection>
</resultMap>
<!--查询学生课程表 一对多-->
<select id="selectone2more" resultMap="BaseResultMap4">
select t1.*,t2.* from students t1 left join subject t2 on t1.stu_id=t2.stu_id
</select>
在实体类中添加 课程属性 并且实现getset tostring和有参无参构造
// A code block
var foo = 'bar';
private int stuId;
private String stuName;
private int stuAge;
private String stuGender;
private int teaId;
private Date stuCreateDate;
//添加教师属性
private Teacher teacher;
//添加课程属性
private List<Subject> subjects;
下面展示代码实现一对多利用map
// An highlighted block
var foo = 'bar';
<!--查询学生课程表 一对多利用map-->
<select id="selectMap" resultType="java.util.Map">
select t1.*,t2.* from students t1 INNER join subject t2 on t1.stu_id=t2.stu_id
</select>
下面展示一些 dao层代码。
// An highlighted block
var foo = 'bar';
//查询学生课程表 一对多 利用map
public List<Map<String,Object>> selectMap();
下面展示一些 测试类循环输出map中的数据。
// An highlighted block
var foo = 'bar';
List<Map<String, Object>> maps = service.selectMap();
for (Map<String,Object> map : maps){
System.out.println(map);
}
System.out.println("查询学生课程表--一对多利用map:"+maps);
运行时出现的错误
- 当启用缓存时要在实体类中实现序列化
- resultMap在不同的mapper文件中的名字也不可以相同
- dao层的方法和mapper中的id需要对应