通俗易懂Mybatis 多对一,一对多

环境搭建

首先在maven中导入坐标,包括,mybatis,jdbc,druid连接池,log4j日志,lombok快速生成pojo

 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <!-- MySql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- druid阿里的数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

druid配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/lyl?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=lyl

然后就是mybatis核心配置文件和mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
    <properties resource="druid.properties"/>
<!--    引入日志-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
<!--    为返回类型起别名-->
    <typeAliases>
        <typeAlias type="com.lyl.Pojo.Teacher" alias="Teacher"/>
        <typeAlias type="com.lyl.Pojo.Student" alias="Student"/>
    </typeAliases>

    <environments default="development">
<!--        默认当前的环境-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--     默认开启连接池-->
            <dataSource type="POOLED">
<!--                数据源配置-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--    为每个mapper映射进行注册-->
    <mappers>
        <mapper class="com.lyl.Dao.StudentMapper"/>
    </mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyl.Dao.StudentMapper">
<!--采用嵌套查询-->
    <select id="findAllStudent" resultType="com.lyl.Pojo.Student">
        select * from student s,teacher t where s.tid =  t.id ;
    </select>

</mapper>

这里的mapper映射文件时在resource目录下的,并与mapper接口同一层次。

 

如果要写在mapper接口下,要让maven识别此配置文件 在pom中配置如下:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

 学生表和老师表(其中学生id是主键,tid是外键关联对应的老师)

 

 两个表结构(映射在实体类pojo上并设置多表查询的属性)这里用的lombok快速生成getter,setter,tostring方法(加上@Data)

 

 

在查询之前我们要大致理解一下mybatis的基本原理

首先是简化了大量jdbc操作,如prestatement预处理,resultset结果集,等jdbc代码的编写,然后就是通过mapper动态代理模式,进行xml配置代替了实现类的编写。其大致流程就是,我先通过加载mybatis配置文件来生成SqlSessionFactory并造出SqlSession的bean,然后通过getMapper方法获取对应的业务,此时我们配置好了mapper映射文件也进行了注册,这时mybatis通过sql语句从数据库查询到了一批结果,在根据我们的配置进行映射,如果我的pojo属性与数据库字段不一致则会报null或者0(看数据类型)

这里由于获取bean的行为是一致的因此封装一个工具类用于获取SqlSession

public class mybatis_xml {
    private static SqlSessionFactory sqlSessionFactory;
    //静态代码块
    static {
        try {
            String resource = "mybatis.xml";
            InputStream inputStream =  Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}

关联 association 【多对一】 

通过学生表查询所有学生所属的授课老师 ,多表查询有两种方法一种是按结果嵌套查询(好理解比较麻烦)一种是子查询法(sql简单不好理解)

问题引入

要想查询所有的学生对应的授课老师,进行连表查询即可

 <select id="findAllStudent" resultType="com.lyl.Pojo.Student">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where s.tid =  t.id ;
    </select>

此时在数据库中是正常的查询出学生对应的所有老师 

 

可是在当使用mybatis时进行测试发现明明数据库有数据问什么teacher是null啊?,这里我们可以想到,由于使用的是一个框架,通过这个框架来代替我们jdbc代码的书写,必然要遵守框架的规范

即我们没有正确的映射数据库的数据!

问题解决

首先按照结果映射,上面我们已经发现了问题,老师的信息没有映射到属性上, 此时我们可以通过ResultMap结果集映射来解决比较复杂的sql语句

配置如下: 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyl.Dao.StudentMapper">
<!--按结果嵌套查询-->
    <select id="findAllStudent" resultMap="StudentByTeacher">
#         这里为了区别老师和学生要设置别名
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where s.tid =  t.id ;
    </select>
    <!--这里的id指定上面的resultmap type其实就是resultType返回类型是Student类,我进行了别名配置   -->
    <resultMap id="StudentByTeacher" type="Student">
        <!--这里进行映射,简单类型用result指明column字段与property属性之间的关系  -->
        <result column="sid" property="id"/>
        <result column="tid" property="tid"/>
        <result column="sname" property="name"/>
        <!--复杂的类型如一个类或者集合,类用association表示一对多,集合用collection表示多对一-->
        <!-- 这里的类型为一个老师对象 -->
        <association property="teacher" javaType="com.lyl.Pojo.Teacher" >
            <result column="tid" property="id"/>
            <result column="tname" property="name"/>
        </association>
    </resultMap>
</mapper>

 运行,成功显示学生和老师的所有信息,如果要显示和数据库一样的查询结果,只需要去掉pojo对应的字段即可

细节处理   

1.可以发现,这里是将所有学生存到一个list集合中,每个行数据代表一个对象,其中该student对象中包含了老师的对象,这也应证了老师对象没有正确的配置到映射中的问题,可以发现输出的形式与mapper接口定义的抽象方法和字段的属性有关。


public interface StudentMapper {
    //返回一个集合其中泛型为学生
    List<Student> findAllStudent();
}

 2.在配置结果集中最重要的一行配置是:(即关于老师第一行映射语句)

<result column="tid" property="id"/>

其这句话联立了老师表和学生表,通过学生的tid传递给到老师的id,而对应的sql则是

where s.tid =  t.id ;

传递了外键tid映射到老师的property id中,并通过where判断了不同学生的tid是否和老师的id相同这也印证了这种按结果嵌套查询的思想,即我先通过sql进行查询,然后得出结果,再按结果进行映射到pojo中,这种方式可以根据需求进行配置结果集,十分灵活,比如当需求变成求每个学生对应老师的名字,这时把外键改成了老师的姓名,然后在将sql中where s.tid = t.id ;该成where s.tname = t.name ;然后在最核心的一句话中将<result column="tid" property="id"/>改成<result column="tname" property="name"/>即可实现老师姓名的传递。

当然还有另一种方式,子查询,也就是上一个查询的结果作为下一个查询的参数使用,即先通过查询学生的tid,在把tid作为参数传递给老师进行查询,最后在映射  

在sql中的语法是:

 

 mapper映射文件:

<!-- 子查询 -->
    <select id="findStudent" resultMap="StudentAndTeacher">
        select * from student
    </select>
    <select id="findTeacher" resultType="Teacher">
        select * from teacher where id=#{tid}
    </select>
    <resultMap id="StudentAndTeacher" type="Student">
        <result column="tid" property="tid"/>
        <association column="tid" property="teacher" javaType="com.lyl.Pojo.Teacher" select="findTeacher">
        </association>
    </resultMap>

这里:javatypes:把sql语句查询出来的结果集,封装给某个类的对象

           select:下一条要执行的sql语句

            column:在上次查询结果集中,用哪些列值作为条件去执下一条sql 

测试结果

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值