Mybatis记录

109 阅读2分钟

一 Mybatis是什么

1.1 介绍

  1. 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory的实例为核心的
  2. SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得,方式是从 XML 配置文件或一个预先配置的 Configuration实例来构建出

1.2 总结

    String resource="mybatis-config.xml";
    //在JDBC中是 xxx.class.getClassLoader().getResourceAsStream("全类名")
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //在JDBC中是 pro.load(inputStream) ,然后Class.forName("驱动")
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  1. 有一个mybatis-config.xml文件,通过上面三行代码读出在mybatis-config.xml文件中配置的数据
  2. 导入的mybaits中的SqlSessionFactoryBuilder—>SqlSessionFactory通过调用其openSession方法->SqlSession

二 从mybatis-xml文件来看Mybatis配置的一些属性

2.1 properties

为了让项目更加工程化,可以创建config.properties在resource文件下,然后通过properties属性将文件加载

2.2 settings

这个属性下有很多子属性,其中比较重要的是logImpl,用于打印Mybatis的日志,将执行结果进行输出

2.3 typeAliases类型别名

为了让一些全类名的书写简化,不用写过多的路径,设置了typeAliases属性进行配置

方式一: 
    将指定包名(com.kallensun.pojo)下的所有的Java Bean在要使用的地方被改成小写的类名。
    例如com.kallensun.pojo.User可以用user进行替代
<typeAliases>
    <package name="com.kallensun.pojo"/>
</typeAliases>
方式二:
       如下User将替代任何需要使用com.kallensun.pojo.User的地方
<typeAliases>
    <typeAlias alias="User" type="com.kallensun.pojo.User"/>
</typeAliases>

此外,按照文档,Java中的数据类型在Mybatis中都完成了映射

2.4 environments

Mybatis可以通过environments属性提供开发/测试/生产不同的环境,

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>

三 XML映射器

3.1 update/insert/delete语句

属性记录

id:
parameterType:

3.2 select 和 resultMap

多对一查询

StudentMapper.xml

    //这里根据sql语句查询结果,但是由于resultMap,会将结果进行映射
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    
    //映射是将上一个查询的结果(数据库表的形式)对Java Bean进行一一映射
    <resultMap id="StudentTeacher" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="tid" column="tid"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher">
        </association>
    </resultMap>
    
    //再进行第二次查询
    <select id="getTeacher" resultType="teacher">
        select * from teacher where id=#{id}
    </select>