MyBatis基本使用及XML配置

概述

MyBatis是一款优秀的持久层框架,避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程,减少了代码的冗余,减少程序员的操作,可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。

github地址

https://github.com/mybatis/mybatis-3/

依赖

<dependencies>
    <!-- Mybatis核心 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.3</version>
    </dependency>
</dependencies>

mybatis配置文件

创建mybatis配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--写好的sql映射文件(EmployeeMapper.xml)注册到全局配置文件(mybatis-config.xml)中-->
    <mappers>
        <mapper resource="xxxMapper.xml"/>
    </mappers>
</configuration>

sql映射文件

sql映射文件xxxMapper.xml

<?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="com.xxx.mybatis.xxxMapper">
<!--namespace:名称空间
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出ID值
-->
    <select id="selectXxx" resultType="com.xxx.mybatis.bean.Employee">
        select id,last_name lastName,gender,email from xxx where id=#{id}
    </select>
</mapper>

基本使用

  1. 根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象

  1. sql映射文件。配置了每一个sql,以及sql的封装规则等

  1. 将sql映射文件注册在全局配置文件中

  1. 写代码

  1. 根据全局配置文件得到SqlSessionFactory

  1. 使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查

一个sqlSession就是代表和数据库的一次会话,用完关闭

  1. 使用sql的唯一标识来告诉MyBatis执行哪个sql,sql都是保存在sql映射文件中的

public class MyBatisTest {

    @Test
    public void test() throws IOException{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取sqlSession实例,能直接执行已经映射的sql语句
        SqlSession openSession = sqlSessionFactory.openSession();
        //第一个参数 sql语句的唯一标识符 第二个参数 执行sql 语句要用的参数
        try {
            Xxx xxx = openSession.selectOne("com.xxx.mybatis.xxxMapper.selectXxx", 1);
            System.out.println(xxx);
        }finally {
            openSession.close();
        }
    }
}

接口式编程

创建Dao接口

public interface XxxMapper {

    public Xxx getXxxById(Integer id);
}

基本使用

public class MyBatisTest{

    public SqlSessionFactory getSqlSessionFactory() throws IOException{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);

    }
    @Test
    public void test01() throws IOException {
        //1.获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //2.获取sqlSession对象
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            //3.获取接口的实现类对象
            //会为接口自动的创建一个代理对象,代理对象去执行增删改查方法,将接口与xml进行绑定
            XxxMapper mapper = openSession.getMapper(XxxMapper.class);
            Xxx xxx = mapper.getXxxById(1);
            System.out.println(mapper.getClass());
            System.out.println(xxx);
        }finally {
            openSession.close();
        }
    }
}

重要的配置文件

  • mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息,系统运行环境信息

  • sql映射文件:保存了每一个sql语句的映射信息

XML 配置

属性(properties)

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。例如:

  • resource:引入类路径下的资源

  • url:引入类路径或者磁盘路径下的资源

<properties resource="dbconfig.properties"></properties>

设置好的属性可以在整个配置文件中用来替换需要动态配置的属性值。比如

<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>

dbconfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

设置(settings)

 <!--settings包含很多重要的设置项
        setting:用来设置每一个设置项
            name:设置项的名字
            value:设置项的取值
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
mapUnderscoreToCamelCase,是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn,默认为false

类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

 <!--typeAliases:别名处理器:可以为我们的Java类型起别名
            别名不区分大小写-->
    <typeAliases>
        <!--typeAlias:为某个Java类型起别名
            type:指定要起别名的类型全类名;默认别名就是类名小写:employee
            alias:指定新的别名-->
        <typeAlias type="com.xxx.mybatis.bean.Employee" alias="emp"/>

        <!--package:为某个包下的所有类批量起别名
            name:指定报名(指定为当前包以及下面所有的后代包的每一个类都起一个默认别名(类名小写))-->
        <package name="com.xxx.mybatis.bean"/>

        <!--批量起别名的情况下,使用@Alias注解为某个类型指定新的别名-->
    </typeAliases>
@Alias("emp")
public class Employee {
}

类型处理器(typeHandlers)

MyBatis 在设置预处理语句(PreparedStatement)中的参数或从结果集中取出一个值时, 都会用类型处理器将获取到的值以合适的方式转换成 Java 类型。

https://mybatis.org/mybatis-3/zh/configuration.html#typeHandlers

插件(plugins)

MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。

https://mybatis.org/mybatis-3/zh/configuration.html#plugins

环境配置(environments)

  <!--environments:环境们,mybatis可以配置多种环境 default指定使用某种环境。可以达到快速切换
            environment:配置一个具体的环境信息:必须有两个标签 id(代表当前环境的唯一标识)
            transactionManager:事务管理器;
                type:事务管理器的类型:JDBC(JDBCTransactionFactory)|MANAGED(Managed)
                    自定义事务管理器:实现JDBCTransactionFactory接口,type指定为全类名
            dataSource:数据源
                type:数据源类型;UNPOOLED|POOLED|JNDI
                自定义数据源:实现DataSourceFactory接口,type是全类名

                 -->
    <environments default="test">
        <environment id="test">
            <transactionManager type=""></transactionManager>
            <dataSource type=""></dataSource>
        </environment>

数据库厂商标识(databaseIdProvider)

MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。 MyBatis 会加载带有匹配当前数据库 databaseId 属性和所有不带 databaseId 属性的语句。 如果同时找到带有 databaseId 和不带 databaseId 的相同语句,则后者会被舍弃。 为支持多厂商特性,只要像下面这样在 mybatis-config.xml 文件中加入 databaseIdProvider 即可

<!--databaseIdProvider,支持数据库厂商的,
              type="DB_VENDOR":VendorDatabaseIdProvider
                  作用就是得到数据库厂商的标识(驱动),mybatis就能根据数据库厂商标识来执行不同的sql
                  MySQL,Oracle,SQL,Server,xxx;
                  -->
    <databaseIdProvider type="DB_VENDOR">
        <!--为不同的数据库厂商起别名-->
        <property name="MySQL" value="mysql"/>
        <property name="Oracle" value="oracle"/>
        <property name="SQL Server" value="sqlserver"/>
    </databaseIdProvider>
    <select id="getEmpById" resultType="com.frx01.mybatis.bean.Employee" databaseId="mysql">
        select id,last_name lastName,gender,email from tbl_employee where id=#{id}
    </select>

映射器(mappers)

定义 SQL 映射语句,首先我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等。

  <!--mappers:将sql映射注册到全局配置中-->
    <mappers>
        <!--mapper:注册一个sql映射
                resource:引用类路径下的sql映射文件
                    mybatis/mapper/EmployeeMapper.xml
                url:引用网络路径或磁盘路径下的sql映射文件
                注册接口
                class:引用(注册)接口
                    1.有sql映射文件,映射文件名必须和接口同名,并且放在与接口同一目录下;
                    2.没有sql映射文件,所有的sql都是利用注解 写在接口上
                    推荐:
                        比较重要的,复制的Dao接口我们来写sql映射文件
                        不重要,简单的Dao接口为了开发快速可以使用注解
                -->
        <!--<mapper resource="EmployeeMapper.xml"/>-->
        <!--<mapper class="com.frx01.mybatis.dao.EmployeeMapperAnnotation"/>-->

        <!--批量注册 要把Mapper.xml与dao层放在一个包下-->
        <package name="com.xxx.mybatis.dao"/>
    </mappers>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

像向日葵一样~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值