一、Mybatis实现多表联查询
1、Mybatis实现多表联查询方式
- 业务装配对两个表写单独的sql语句,在业务(service)把查询结果进行联合。
- 使用Auto Mapping特性,在实现两个表联合查询时通过别名完成自动映射。
- 使用Mybatis的标签进行实现
2、多表查询时类中包含另一个对象的分类
二、resultMap标签
1、标签单表中的映射
写在
select * from student where tid = #{0}
在TeacherMapper.xml中添加查询全部,然后通过来装配其它的,代码:
还是和查询单个对象一样这里中使用来匹配集合,其中property还是类中的属性名,select是要执行的sql语句,column为要传递的参数字段。
5、使用实现加载集合数据(联合查询方式)
只需要写一条SQL,在TeacherMapper.xml中完成,对于老师的属性在中直接用或进行装配(将字段别名与属性匹配),对于Student对象集合用标签来映射,其中 property还是代表在类中该对象集合属性的名称 另外要设置ofType表示返回集合的泛型,其它的还一次对应匹配即可。具体代码实例:
<!-- 使用联合查询 -->
<resultMap type="Teacher" id="teacMap1">
<id column="tid" property="id"/>
<result column="tname" property="name"/>
<collection property="list" ofType="Student">
<id column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="age" property="age"/>
<result column="tid1" property="tid"/>
</collection>
</resultMap>
<select id="selAll1" resultMap="teacMap1">
select t.id tid, t.name tname, s.id sid, s.name sname,age ,s.tid tid1
from teacher t left join student s on t.id = s.tid
</select>
三、使用Auto Mapping结合别名实现多表查询
- 只能使用多表联合查询方式.
- 要求:查询出的列别和属性名相同.
- 实现方式,在 SQL 是关键字符,两侧添加反单引号
- 只能适用于单个对象
代码实例:
<select id="selAll" resultType="student">
select t.id `teacher.id`,t.name `teacher.name`,s.id id,s.name name,age,tid
from student s LEFT JOIN teacher t on t.id=s.tid
</select>
四、Mybatis注解
- 注解:为了简化配置文件.
- Mybatis 的注解简化 mapper.xml 文件.
- 如果涉及动态 SQL 依然使用 mapper.xml
- mapper.xml 和注解可以共存.
- 使用注解时 mybatis.xml 中使用
- 或
一般实例:
实现查询:
@Select(“select * from teacher”)
List selAll();
实现新增
@Insert(“insert into teacher values(default,#{name})”)
int insTeacher(Teacher teacher);
将主键带回来的方式:设置@Options注解并配置(useGeneratedKeys=true,keyProperty=”id”)
@Insert("insert into log values(default,#{accOut},#{accIn},#{money})")
@Options(useGeneratedKeys=true,keyProperty="id")
int insLog(Log log);
还没有评论,来说两句吧...