MyBatis框架学习(一)

一、MyBatis简介

1)MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
2)MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
3)MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录
4)半自动ORM(Object Relation Mapping)框架
为什么要使用MyBatis-与现有持久化技术的对比
1)JDBC
①SQL夹在Java代码块里,耦合度高导致硬编码内伤
②维护不易且实际开发需求中sql是有变化,频繁修改的情况多见
2)Hibernate和JPA
①长难复杂SQL,对于Hibernate而言处理也不容易
②内部自动生产的SQL,不容易做特殊优化
③基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难。导致数据库性能下降

二、环境准备

<1>、环境搭建

https://github.com/mybatis/mybatis-3/下载相对应版本的MyBatis压缩包,
log4j.jar和mysql-connector-java-5.1.37-bin.jar可以从
https://mvnrepository.com/下载然后放在工程的lib文件夹下

<2>、配置文件

创建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="jjdbc:mysql://localhost:3306/big_data"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

三、入门

<1>、第一个简单程序

首先我们要先查看MyBatis压缩包提供的文档,可以帮助我们快速上手。
在这里插入图片描述
利用xml的方式创建一个SqlSessionFactory,并且给我们提供了代码,这是MyBatis的主要配置

		String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

不利用xml方式创建SqlSessionFactory
在这里插入图片描述
通过 SqlSessionFactory获取SqlSession:
在这里插入图片描述

SqlSession session = sqlSessionFactory.openSession();

SqlSession创建之后执行了一次搜索操作:

	try {
      Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    } finally {
      session.close();
    }

session.selectOne第一个参数是使用一个唯一标识符匹配,第二个参数是执行SQL语句时要用到的参数对象。
在这里插入图片描述
配置SQL的映射文件

	<mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>

程序的执行顺序就是:
1.String resource=“mybatis-config.xml”,从下面去自动匹配到这个xml文件
2.再由这个文件找到了Mapper文件,从mapper文件中又找到由id对应的唯一匹配的sql语句

	<select id="selectEmployee" resultType="mybatis.beans.Employee">
    		select * from table_employee where id = #{id}
  	 </select>

测试代码如下:

	 /**
     * MyBatis HelloWorld 小结:
     * 两个重要的配置文件
     * mybatis-config.xml :全局配置文件 , 数据库连接信息、 引入SQL映射文件等....
     * EmployeeMapper.xml :SQL映射文件 , 配置增删改查的SQL语句的映射
     * <p>
     * 两个重要的对象
     * SqlSessionFactory: SqlSession的工厂对象, 主要是用于获取SqlSession对象
     * SqlSession:  Java程序与数据库的会话对象.可以理解为是对Connection的封装.
     */

    @Test
    public void testSqlSessionFactory() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        System.out.println(sqlSessionFactory);

        SqlSession session = sqlSessionFactory.openSession();

        System.out.println(session);

        try {
            /**
             *  statement    Unique identifier matching the statement to use.
             *  			 SQL语句的唯一标识
             parameter    A parameter object to pass to the statement.
             执行SQL需要用到的参数
             */
            Employee employee = session.selectOne("suibian.selectEmployee", 1001);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }

对应get、set方法的类Employee

public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;

    private Department department;
    public Employee() {
    }

    public Employee(Integer id, String lastName, String email, Integer gender) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                '}';
    }
}
<2>、基于Mapper接口的CRUD操作

完成两个绑定
① Mapper接口与Mapper映射文件的绑定
在Mppper映射文件中的标签中的namespace中必须指定Mapper接口
的全类名
② Mapper映射文件中的增删改查标签的id必须指定成Mapper接口中的方法名.

@Test
    public void testHelloWorldMapper() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            //mapper接口: dao接口
            /**
             * 两个绑定:
             * 	 1. Mapper接口与SQL映射文件的绑定.  映射文件的namespace的值必须指定成接口的全类名.
             * 	 2. Mapper接口的方法与SQL映射文件的具体SQL语句的绑定    SQL语句的id值  必须指定成接口的方法名.
             *
             * Mapper接口开发的好处:
             * 	 1. 有更明确的类型
             * 	 2. 接口本身: 接口本身就是抽象. 抽出了规范.
             * 			EmployeeMapper:    EmployeeDaoJdbcImpl 、 EmployeeDaoHibernateImpl、MyBatis代理实现类
             */
            //获取MyBatis为Mapper接口生成的代理实现类对象
            EmployeeMapper dao = session.getMapper(EmployeeMapper.class);
            Employee employee = dao.getEmployeeById(1002);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
	<select id="getEmployeeById" resultType="employee">
		select id, last_name lastName, email, gender from table_employee where id = #{id}
	</select>
public interface EmployeeMapper {
    //根据id查询Employee
    Employee getEmployeeById(Integer id);
}
<3>、MyBatis全局配置文件
(1)、properties属性

properties:属性配置
resource:引入类路径下的属性文件
url:引入网络路径或者是磁盘路径下的属性文件
在这里插入图片描述

(2)、settings设置
<!--2、settings:包含了很多重要的设置项-->
    <settings>
        <!--映射下滑线到驼峰命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延时加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--配置按需加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
(3)、typeAliases别名处理

在这里插入图片描述
可以使我们的命名变得更加精简,当使用到全类名的时候就感受到好处了,alias可以不写这种情况下默认的就是类名。
在这里插入图片描述
支持批量进行精简化,只需要指定包名;当别名冲突,可以使用@Alias()注解为冲突的类具体指定别名
在这里插入图片描述

(4)、environments环境配置

在这里插入图片描述
作用是给不同SQL语句建出映射关系,并且可以帮我们指定在不同需求时候搭建不同的环境,而在开发,测试,上线的环境都是不相同的;这些都可以在default中指明
在这里插入图片描述
事务管理器:transactionManager
是environments内所包含的其中一个属性,这个一般和spring结合起来使用
在这里插入图片描述
dataSource:分为POOLED和UNPOOLED两种,使用连接池和不使用连接池
在这里插入图片描述
在这里插入图片描述

(5)、mapper映射

引入SQL映射文件
< mapper>: 引入一个SQL映射文件
resource:引入类路径下的SQL映射文件
< package>:批量引入SQL映射文件
要求:SQL映射文件必须与Mapper接口同名同位置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值