这篇文章写了以下几个简单的例子,用来说明MyBatis多标联查基本语法

1.sql片段的用法

2.一对多查询

3.多条sql的一对多查询

4.多对一查询

5.多条sql一对多查询

6、多对多查询

这里沿着接口→小配置的路线写了,测试类就是遍历输出结果:

一、接口:

 package cn.sohappy.acourses.course0921;

 import cn.sohappy.acourses.bean.BillManyToOne;
import cn.sohappy.acourses.bean.UserOneToMany;
import cn.sohappy.bean.Smbms_user; import java.util.List; public interface IUserDAO {
//01.sql片段,查询所有user
List<Smbms_user> findAll();
//02.oneToMany,传入user,返回包含账单信息的user
UserOneToMany getUserOneToManyBills(UserOneToMany user);
//03.oneToMany,多条sql查询,传入user,返回包含账单信息的user
UserOneToMany getUserOneToManyBillsMultiSQL(UserOneToMany user);
//04.manyToOne,传入bill,返回包含用户信息的bill
BillManyToOne getBillManyToOneUser(BillManyToOne bill);
//05.manyToOne,多条sql查询,传入bill,返回包含用户信息的bill
BillManyToOne getBillManyToOneUserMultiSQL(BillManyToOne bill);
}

二、小配置

先实现第一个方法

1、List<Smbms_user> findAll();查询所有user的编号,名字,密码

小配置的配置头

<?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="cn.sohappy.acourses.course0921.IUserDAO">
<!--此处是代码-->
</mapper>

以下省略配置头

  <sql id="columns">
userCode,userName,userPassword
</sql>
<resultMap id="mUser" type="cn.sohappy.bean.Smbms_user" autoMapping="false">
<id property="username" column="userName"/>
<result property="userpassword" column="userPassword"/>
<result property="usercode" column="userCode"/>
</resultMap>
<!--用<include refid="columns"/>代替*-->
<select id="findAll" resultMap="mUser">
select <include refid="columns"/> from smbms_user
</select>

2、UserOneToMany getUserOneToManyBills(UserOneToMany user);

查询某个用户的账单信息,首先将账单List植入用户类中(第11行)

 package cn.sohappy.acourses.bean;

 import java.util.List;

 public class UserOneToMany {
private Long id;
private String usercode;
private String username; //a user has lots of bills
private List<BillManyToOne> bills; //getter and setter
}

小配置代码:

resultMap中property是对象的属性名,column是数据表中的字段名。collection是UserOneToMany对象中植入的泛型集合属性List<BillManyToOne> bills

语法是:<collection property="bills" ofType="cn.sohappy.acourses.bean.BillManyToOne">...code...</collection>

 <!--.oneToMany-->
<resultMap id="UserOneToManyBills" type="cn.sohappy.acourses.bean.UserOneToMany" autoMapping="false">
<id property="id" column="u_id"/>
<result property="username" column="userName"/>
<collection property="bills" ofType="cn.sohappy.acourses.bean.BillManyToOne">
<id property="id" column="b_id"/>
<result property="productname" column="productName"/>
<result property="billcode" column="billCode"/>
</collection>
</resultMap>
<select id="getUserOneToManyBills" resultMap="UserOneToManyBills">
<!--不好,id重名了,起个别名吧-->
select smbms_user.id as u_id,userName,smbms_bill.id as b_id,productName,billCode from smbms_user,smbms_bill
where smbms_user.id=smbms_bill.createdBy and userCode=#{usercode}
</select>

3、UserOneToMany getUserOneToManyBillsMultiSQL(UserOneToMany user);

该方法通过多条sql查询user和其账单

小配置代码:其中#{**}是占位符

 <!--.oneToMany多条sql-->
<resultMap id="UserOneToManyBillsMultiSQL" type="cn.sohappy.acourses.bean.UserOneToMany" autoMapping="false">
<id property="id" column="id"/>
<result property="username" column="userName"/>
<!--下行的select为第二条sql名,column为第一条sql的字段名,其唯一值作为第二条sql的条件-->
<collection property="bills" ofType="cn.sohappy.acourses.bean.BillManyToOne" select="selectBillsByUser" column="id"/>
</resultMap>
<select id="selectBillsByUser" resultType="cn.sohappy.acourses.bean.BillManyToOne">
select * from smbms_bill where createdBy=#{**}
</select>
<select id="getUserOneToManyBillsMultiSQL" resultMap="UserOneToManyBillsMultiSQL">
select * from smbms_user where userCode=#{usercode}
</select>

4、BillManyToOne getBillManyToOneUser(BillManyToOne bill);

传入bill,返回包含用户信息的bill,这里需要在bill类中植入user属性及相应getter and setter:private UserOneToMany user;

小配置代码:这里使用的语法是:<association property="user" javaType="cn.sohappy.acourses.bean.UserOneToMany">...code...</association>

 <!--.manyToOne-->
<resultMap id="BillManyToOneUser" type="cn.sohappy.acourses.bean.BillManyToOne" autoMapping="false">
<id property="id" column="b_id"/>
<result property="billcode" column="billCode"/>
<association property="user" javaType="cn.sohappy.acourses.bean.UserOneToMany">
<id property="id" column="u_id"/>
<result property="usercode" column="userCode"/>
<result property="username" column="userName"/>
</association>
</resultMap>
<select id="getBillManyToOneUser" resultMap="BillManyToOneUser">
select smbms_user.id as u_id,userCode,userName,smbms_bill.id as b_id,billCode from smbms_user,smbms_bill
where smbms_user.id=smbms_bill.createdBy and billCode=#{billcode}
</select>

5.BillManyToOne getBillManyToOneUserMultiSQL(BillManyToOne bill);多条sql多对一查询

小配置代码:

 <!--.manyToOne多条sql-->
<resultMap id="BillManyToOneUserMultiSQL" type="cn.sohappy.acourses.bean.BillManyToOne" autoMapping="false">
<id property="id" column="id"/>
<result property="billcode" column="billCode"/>
<association property="user" javaType="cn.sohappy.acourses.bean.UserOneToMany" autoMapping="false" select="selectUserByCreatedBy" column="CreatedBy">
<id property="id" column="id"/>
<result property="usercode" column="userCode"/>
<result property="username" column="userName"/>
</association>
</resultMap>
<select id="selectUserByCreatedBy" resultType="cn.sohappy.acourses.bean.UserOneToMany">
select * from smbms_user where id=#{**}
</select>
<!--这里需要查找公共字段createdBy作为association中的column参数-->
<select id="getBillManyToOneUserMultiSQL" resultMap="BillManyToOneUserMultiSQL">
select id,billCode,createdBy from smbms_bill where billCode=#{billcode}
</select>

最后写下多对多查询

其实多对多查询和一对多查询是一样的,只不过表中可能没有公共字段,要借助第三张表。

举个例子:根据老师id查询他所教授学生的id

下面建立三张表:

这是student表

这是老师表

这是第三张表

步骤和一对多是一样的,先生成实体类,然后在老师中植入学生List

创建接口,写个方法:

 package cn.sohappy.acourses.course0923;

 import cn.sohappy.acourses.bean.Teachert14;

 public interface ITeacherDAO {
Teachert14 findStudentsByTeacher(Teachert14 teacher);
}

下面直接写小配置了:

 <?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="cn.sohappy.acourses.course0923.ITeacherDAO">
<resultMap id="mTeacher" type="cn.sohappy.acourses.bean.Teachert14">
<id property="tid" column="tid"/>
<result property="tname" column="tname"/>
<collection property="studentt14s" ofType="cn.sohappy.acourses.bean.Studentt14">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
</collection>
</resultMap>
<select id="findStudentsByTeacher" resultMap="mTeacher">
select studentt14.sid,sname,teachert14.tid,tname from studentt14,teachert14,teacher_studentt14
where studentt14.sid=teacher_studentt14.sid and teachert14.tid=teacher_studentt14.tid
and teachert14.tid=#{tid}
</select>
</mapper>

最后附上测试类和MyBatis工具类:

测试类:

 package cn.test;

 import cn.sohappy.acourses.bean.Studentt14;
import cn.sohappy.acourses.bean.Teachert14;
import cn.sohappy.acourses.course0923.ITeacherDAO;
import cn.sohappy.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test; public class test20170923 {
//多对多,借助第三张表
@Test
public void findStudentsByTeacher(){
SqlSession session = MyBatisUtil.getSession();
ITeacherDAO mapper = session.getMapper(ITeacherDAO.class);
Teachert14 teachert14 = new Teachert14();
teachert14.setTid(1L);
Teachert14 teacher = mapper.findStudentsByTeacher(teachert14);
for (Studentt14 item:teacher.getStudentt14s()) {
System.out.println(item.getSname());
}
}
}

MyBatis工具类:

 package cn.sohappy.util;

 import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.InputStream; public class MyBatisUtil {
private static InputStream is;
private static SqlSessionFactory sqlSessionFactory;
static {
try {
is=Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory= new SqlSessionFactoryBuilder().build(is);
}
private MyBatisUtil(){}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}

SSM(二)MyBatis多表联查的更多相关文章

  1. 使用mybatis多表联查的时候结果异常及springmvc的理解

    今天使用mybatis多表联查的时候,在dos窗口查询时可以出结果集,但是使用mybatis查询的时候最后返回的结果只有最后一个结果 然后研究了半天没弄出来,后来无意中发现添加了最外层从表的ID字段后 ...

  2. 【mybatis】mybatis多表联查,存在一对多关系的,实体中使用List作为字段接收查询结果的写法

    实体如下: IntegralGoods  积分商品 IntegralGoodsImg 积分商品图片 ShelfLog 积分商品自动上架记录 IntegralGoods :IntegralGoodsIm ...

  3. mybatis 多表联查,多个实体类,如何返回一个List?(表太多,字段太多的问题)

    原文:https://ask.csdn.net/questions/674166 自己重新定义一个实体类 把查询结果放到这个实体类中,实体类包含所有的查询结果的字段 一个更好的办法,我发现你这关联表所 ...

  4. mybatis.net 多表联查

    mybatis.net针对多表联查,其实不用讲联查出的所有的列全部做一个新的resultMap,我们完全可以通过集成关系来实现,真是上一次说的懒加载,在一定程度上可以提高其性能,但这并不是说懒加载性能 ...

  5. Mybatis中多表联查,查询出来的字段出现重名,造成数据异常的解决方法!

    在做一对多出现的问题,引发的思考:当数据库表中,主表的主键id和明细表的中的字段名相同时怎么办?Mybatis进行自动映射赋值的时候会不会出现异常?                      注意:M ...

  6. Java基础-SSM之mybatis一对一关联

    Java基础-SSM之mybatis一对一关联 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备测试环境(创建数据库表)  1>.创建husbands和wifes表并建 ...

  7. Java基础-SSM之mybatis多对多关联

    Java基础-SSM之mybatis多对多关联 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备测试环境(创建数据库表) 1>.创建teas,stus,links表 u ...

  8. Java基础-SSM之mybatis一对多和多对一关系映射

    Java基础-SSM之mybatis一对多和多对一关系映射 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备测试环境(创建数据库表)  1>.创建customers表: ...

  9. Java基础-SSM之mybatis的树形控件(自关联)

    Java基础-SSM之mybatis的树形控件(自关联) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备测试环境(创建数据库表) 1>.创建areas表: use y ...

随机推荐

  1. [WebGL入门]十一,着色器编译器和连接器

    注意:文章翻译http://wgld.org/,原作者杉本雅広(doxas).文章中假设有我的额外说明.我会加上[lufy:].另外.鄙人webgl研究还不够深入.一些专业词语,假设翻译有误.欢迎大家 ...

  2. c#引用相等性比较(ReferenceEquals)

    Object.ReferenceEquals方法原型 public static bool ReferenceEquals( object objA, object objB) namespace T ...

  3. WPF与缓动(一) N次缓动

    原文:WPF与缓动(一) N次缓动   WPF与缓动(一)  N次缓动                                                                  ...

  4. aravel 之父 Taylor Otwell :我是如何工作的

    知名 PHP Web 开发框架 Laravel 之父 Taylor Otwell 发文描述了自己的日常工作状态:全职做 Laravel ,朝八晚五,使用 Sublime Text 3 写代码,终端使用 ...

  5. x:key和x:name

    x:Key用在xaml Resources,ResourceDictionary需要key来访问x:Name用在ResourceDictionary以外任何地方,可以使用x:Name在code-beh ...

  6. redis zincrby zadd 遇到的问题

    在维护代理池时 报错1: zincrby(REDIS_KEY,proxy,-1)redis.exceptions.ResponseError: value is not a valid float 查 ...

  7. ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区 1 引言 1.1 读者定位 我们假设用户在阅读本指南前应已具备以下知识: · 熟悉W ...

  8. 基于VUE实现的新闻后台管理系统-一

    基于VUE实现的新闻后台管理系统 前段时间拿到一个关于新闻后台的API,测试数据库使用SQLite,Restful服务是用Go写的,只要运行特定环境下的脚本(run.*)就会启动一个服务,依次后台为接 ...

  9. 修改用户名后TSF出现"需要本地工作区。工作区 xxx 并未驻留在本计算机上"

    解决方法就是:1,打开vs下的"开发人员命令提示"2,按下面格式输入命令:tf workspaces /collection:http://192.168.0.110:8080/t ...

  10. Entity Framework的查询

    Entity Framework是个好东西,虽然没有Hibernate功能强大,但使用更简便.今天整理一下常见SQL如何用EF来表达,Func形式和Linq形式都会列出来(本人更喜欢Func形式). ...