Mybatis框架系列二之------MyBatis 框架快速入门

1,590 阅读8分钟

​本文已参与「新人创作礼」活动,一起开启掘金创作之路。

 Mybatis框架系列二之------MyBatis 框架快速入门

一、入门案例

1.准备Mybatis

2.搭建Mybatis的开发环境

1).创建 mysql 数据库和表

2).创建 maven 工程.%E5%88%9B%E5%BB%BA%20maven%20%E5%B7%A5%E7%A8%8B)

4).加入 maven 坐标.%E5%8A%A0%E5%85%A5%20maven%20%E5%9D%90%E6%A0%87)

5).加入 maven 插件.%E5%8A%A0%E5%85%A5%20maven%20%E6%8F%92%E4%BB%B6)

6).编写 Student 实体类.%E7%BC%96%E5%86%99%20Student%20%E5%AE%9E%E4%BD%93%E7%B1%BB)

7).编写 Dao 接口 StudentDao.%E7%BC%96%E5%86%99%20Dao%20%E6%8E%A5%E5%8F%A3%20StudentDao)

8).编写 Dao 接口 Mapper 映射文件 StudentDao.xml.%E7%BC%96%E5%86%99%20Dao%20%E6%8E%A5%E5%8F%A3%20Mapper%20%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6%20StudentDao.xml)

9).创建 MyBatis 主配置文件.%E5%88%9B%E5%BB%BA%20MyBatis%20%E4%B8%BB%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6)

10).创建测试类 MyBatisTest.%E5%88%9B%E5%BB%BA%E6%B5%8B%E8%AF%95%E7%B1%BB%20MyBatisTest)

二、基本的CURD

1、insert

1).StudentDao 接口中增加方法

2). StudentDao.xml 加入 sql 语句

3).增加测试办法

2、update

1)StudentDao 接口中增加方法

2)StudentDao.xml 增加 sql 语句

3)增加测试方法

3、delete

1)StudentDao 接口中增加方法

2)StudentDao.xml 增加 sql 语句

3)增加测试方法

三、MyBatis 对象分析

1.对象使用

1)Resources 类

2)SqlSessionFactoryBuilder 类

3)SqlSessionFactory 接口

4)SqlSession 接口

2.创建工具类

1)创建 MyBatisUtil 类

2)使用 MyBatisUtil 类

四、MyBatis 使用传统 Dao 开发方式

1.Dao开发

1)创建 Dao 接口实现类

2)实现接口中 select 方法

3)实现接口中 insert 方法

4)实现接口中 update 方法

5)实现接口中 delete 方法

2、传统 Dao 开发方式的分析

Github项目地址


Mybatis框架系列二之------MyBatis 框架快速入门

一、入门案例

MyBatis 开发准备
搭建 MyBatis 开发环境,实现第一个案例

1.准备Mybatis

下载 mybatis

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

2.搭建Mybatis的开发环境

1).创建 mysql 数据库和表

数据库名 mybatis ;表名 student

CREATE TABLE `student` (
`id` int(11) NOT NULL ,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2).创建 maven 工程

  • 使用IDEA编辑器创建 maven 工程,模板信息如下:

  • 删除默认创建的 App 类文件

4).加入 maven 坐标

pom.xml 加入 maven 坐标:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>
</dependencies>

5).加入 maven 插件

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory><!--所在的目录-->
            <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

6).编写 Student 实体类

创建包 com.bjpowernode.domain, 包中创建 Student 类

package com.bjpowernode.domain;
/**
* <p>Description: 实体类 </p>
* <p>Company: http://www.bjpowernode.com
*/
public class Student {
//属性名和列名一样
private Integer id;
private String name;
private String email;
private Integer age;
// set ,get , toString
}

7).编写 Dao 接口 StudentDao

创建 com.bjpowernode.dao 包,创建 StudentDao 接口

package com.bjpowernode.dao;

import com.bjpowernode.domain.Student;

import java.util.List;

//接口操作student表
public interface StudentDao {

    //查询student表的所有的数据
    public List<Student> selectStudents();
}

8).编写 Dao 接口 Mapper 映射文件 StudentDao.xml

**要求:\

  1. 在 dao 包中创建文件 StudentDao.xml\
  2. 要 StudentDao.xml 文件名称和接口 StudentDao 一样,区分大小写的一样。**
<?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.bjpowernode.dao.StudentDao">
    <!--
       select:表示查询操作。
       id: 你要执行的sql语法的唯一标识, mybatis会使用这个id的值来找到要执行的sql语句
           可以自定义,但是要求你使用接口中的方法名称。

       resultType:表示结果类型的, 是sql语句执行后得到ResultSet,遍历这个ResultSet得到java对象的类型。
          值写的类型的全限定名称
    -->
    <select id="selectStudents" resultType="com.bjpowernode.domain.Student" >
        select id,name,email,age from student order by id
    </select>
</mapper>

9).创建 MyBatis 主配置文件

项目 src/main 下创建 resources 目录,设置 resources 目录为 resources root
创建主配置文件:名称为 mybatis.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="mydev">  
        <environment id="mydev">
            <transactionManager type="JDBC"/>
            <!--
               dataSource:表示数据源,连接数据库的
                  type:表示数据源的类型, POOLED表示使用连接池
            -->
            <dataSource type="POOLED">
                <!--
                   driver, user, username, password 是固定的,不能自定义。
                -->
                <!--数据库的驱动类名-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!--连接数据库的url字符串-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
                <!--访问数据库的用户名-->
                <property name="username" value="root"/>
                <!--密码-->
                <property name="password" value="659647"/>
            </dataSource>
        </environment>
    </environments>

    <!-- sql mapper(sql映射文件)的位置-->
    <mappers>
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
    </mappers>
</configuration>

10).创建测试类 MyBatisTest

src/test/java/com/bjpowernode/ 创建 MyBatisTest.java 文件

package com.bjpowernode;

import com.bjpowernode.domain.Student;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {
    //测试方法,测试功能
    @Test
    public void testInsert() throws IOException {

        //访问mybatis读取student数据
        //1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess)
        String config="mybatis.xml";
        //2.读取这个config表示的文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建了SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
        //4.创建SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.获取SqlSession对象,从SqlSessionFactory中获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //6.【重要】指定要执行的sql语句的标识。  sql映射文件中的namespace + "." + 标签的id值
        //String sqlId = "com.bjpowernode.dao.StudentDao" + "." + "selectStudents";
        String sqlId = "com.bjpowernode.dao.StudentDao.selectStudents";
        //7. 重要】执行sql语句,通过sqlId找到语句
        List<Student> studentList = sqlSession.selectList(sqlId);
        //8.输出结果
        //studentList.forEach( stu -> System.out.println(stu));
        for(Student stu : studentList){
            System.out.println("查询的学生="+stu);
        }
        //9.关闭SqlSession对象
        sqlSession.close();
    }
}

二、基本的CURD

查询一个 selectOne
insert ,update ,delete

1、insert

1).StudentDao 接口中增加方法

int insertStudent(Student student);

2). StudentDao.xml 加入 sql 语句

<insert id="insertStudent">
    insert into student(id,name,email,age)
    values(#{id},#{name},#{email},#{age})
</insert>

3).增加测试办法

@Test
public void testInsert() throws IOException {
    //1.mybatis 主配置文件
    String config = "mybatis-config.xml";
    //2.读取配置文件
    InputStream in = Resources.getResourceAsStream(config);
    //3.创建 SqlSessionFactory 对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //4.获取 SqlSession
    SqlSession session = factory.openSession();
    //5.创建保存数据的对象
    Student student = new Student();
    student.setId(1005);
    student.setName("张丽");
    student.setEmail("zhangli@163.com");
    student.setAge(20);
    //6.执行插入 insert
    int rows = session.insert(
    "com.bjpowernode.dao.StudentDao.insertStudent",student);
    //7.提交事务
    session.commit();
    System.out.println("增加记录的行数:"+rows);
    //8.关闭 SqlSession
    session.close();
}

2、update

1)StudentDao 接口中增加方法

int updateStudent(Student student);

2)StudentDao.xml 增加 sql 语句

<update id="updateStudent">
    update student set age = #{age} where id=#{id}
</update>

3)增加测试方法

@Test
public void testUpdate() throws IOException {
    //1.mybatis 主配置文件
    String config = "mybatis-config.xml";
    //2.读取配置文件
    InputStream in = Resources.getResourceAsStream(config);
    //3.创建 SqlSessionFactory 对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //4.获取 SqlSession
    SqlSession session = factory.openSession();
    //5.创建保存数据的对象
    Student student = new Student();
    student.setId(1005);//要修改的 id
    student.setAge(30); //要修改的年龄值
    //6.执行更新 update
    int rows = session.update(
        "com.bjpowernode.dao.StudentDao.updateStudent",student);
    //7.提交事务
    session.commit();
    System.out.println("修改记录的行数:"+rows);
    //8.关闭 SqlSession
    session.close();
}

3、delete

1)StudentDao 接口中增加方法

int deleteStudent(int id);

2)StudentDao.xml 增加 sql 语句

<delete id="deleteStudent">
    delete from student where id=#{studentId}
</delete>

3)增加测试方法

@Test
public void testDelete() throws IOException {
    //1.mybatis 主配置文件
    String config = "mybatis-config.xml";
    //2.读取配置文件
    InputStream in = Resources.getResourceAsStream(config);
    //3.创建 SqlSessionFactory 对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //4.获取 SqlSession
    SqlSession session = factory.openSession();
    //5.删除的 id
    int id = 1001;
    //6.执行删除 delete
    int rows = session.delete(
        "com.bjpowernode.dao.StudentDao.deleteStudent",id);
    //7.提交事务
    session.commit();
    System.out.println("修改记录的行数:"+rows);
    //8.关闭 SqlSession
    session.close();
}

三、MyBatis 对象分析

1.对象使用

1)Resources 类

       Resources 类,顾名思义就是资源,用于读取资源文件。其有很多方法通过加载并解析资源文件,返回不同类型的 IO 流对象。

2)SqlSessionFactoryBuilder 类

      SqlSessionFactory 的 创 建 , 需 要 使 用 SqlSessionFactoryBuilder 对 象 的 build() 方 法 。 由 于SqlSessionFactoryBuilder 对象在创建完工厂对象后,就完成了其历史使命,即可被销毁。所以,一般会将该 SqlSessionFactoryBuilder 对象创建为一个方法内的局部对象,方法结束,对象销毁。

3)SqlSessionFactory 接口

       SqlSessionFactory 接口对象是一个重量级对象(系统开销大的对象),是线程安全的,所以一个应用只需要一个该对象即可。创建 SqlSession 需要使用 SqlSessionFactory 接口的的 openSession()方法

  • openSession(true):创建一个有自动提交功能的 SqlSession
  • openSession(false):创建一个非自动提交功能的 SqlSession,需手动提交
  • openSession():同 openSession(false)

4)SqlSession 接口

      SqlSession 接口对象用于执行持久化操作。一个 SqlSession 对应着一次数据库会话,一次会话以SqlSession 对象的创建开始,以 SqlSession 对象的关闭结束。
SqlSession 接口对象是线程不安全的,所以每次数据库会话结束前,需要马上调用其 close()方法,将其关闭。再次需要会话,再次创建。 SqlSession 在方法内部创建,使用完毕后关闭。

2.创建工具类

1)创建 MyBatisUtil 类

package com.bjpowernode.utils;

public class MyBatisUtils {

    private  static  SqlSessionFactory factory = null;
    static {
        String config="mybatis.xml"; // 需要和你的项目中的文件名一样
        try {
            InputStream in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象,使用SqlSessionFactoryBuild
            factory = new SqlSessionFactoryBuilder().build(in);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //获取SqlSession的方法
    public static SqlSession getSqlSession() {
        SqlSession sqlSession  = null;
        if( factory != null){
            sqlSession = factory.openSession();// 非自动提交事务
        }
        return sqlSession;
    }
}

2)使用 MyBatisUtil 类

@Test
public void testUtils() throws IOException {
    SqlSession session = MyBatisUtil.getSqlSession();
    List<Student> studentList = session.selectList(
        "com.bjpowernode.dao.StudentDao.selectStudents");
    studentList.forEach( student -> System.out.println(student));
    session.close();
}

四、MyBatis 使用传统 Dao 开发方式

1.Dao开发

1)创建 Dao 接口实现类

public class StudentDaoImpl implements StudentDao

2)实现接口中 select 方法

public List<Student> selectStudents() {
    SqlSession session = MyBatisUtil.getSqlSession();
    List<Student> studentList = session.selectList(
        "com.bjpowernode.dao.StudentDao.selectStudents");
    session.close();
    return studentList;
}

测试查询操作:

MyBatisTest 类中创建 StudentDaoImpl 对象
public class MyBatisTest {
    StudentDao studentDao = new StudentDaoImpl();
}
@Test
public void testSelect() throws IOException {
    final List<Student> studentList = studentDao.selectStudents();
    studentList.forEach( stu -> System.out.println(stu));
}

3)实现接口中 insert 方法

public int insertStudent(Student student) {
    SqlSession session = MyBatisUtil.getSqlSession();
    int nums = session.insert(
        "com.bjpowernode.dao.StudentDao.insertStudent",student);
    session.commit();
    session.close();
    return nums;
}

测试 insert

@Test
public void testInsert() throws IOException {
    Student student = new Student();
    student.setId(1006);
    student.setName("林浩");
    student.setEmail("linhao@163.com");
    student.setAge(26);
    int nums = studentDao.insertStudent(student);
    System.out.println("使用 Dao 添加数据:"+nums);
}

4)实现接口中 update 方法

public int updateStudent(Student student) {
    SqlSession session = MyBatisUtil.getSqlSession();
    int nums = session.insert(
        "com.bjpowernode.dao.StudentDao.updateStudent",student);
    session.commit();
    session.close();
    return nums;
}

测试 update

@Test
public void testUpdate() throws IOException {
    Student student = new Student();
    student.setId(1006);
    student.setAge(28);
    int nums = studentDao.updateStudent(student);
    System.out.println("使用 Dao 修改数据:"+nums);
}

5)实现接口中 delete 方法

public int deleteStudent(int id) {
    SqlSession session = MyBatisUtil.getSqlSession();
    int nums = session.insert(
        "com.bjpowernode.dao.StudentDao.deleteStudent",1006);
    session.commit();
    session.close();
    return nums;
}

测试 delete

@Test
public void testDelete() throws IOException {
    int nums = studentDao.deleteStudent(1006);
    System.out.println("使用 Dao 修改数据:"+nums);
}

2、传统 Dao 开发方式的分析

        在前面例子中自定义 Dao 接口实现类时发现一个问题:Dao 的实现类其实并没有干什么实质性的工作,它仅仅就是通过 SqlSession 的相关 API 定位到映射文件 mapper 中相应 id 的 SQL 语句,真正对 DB 进行操作的工作其实是由框架通过 mapper 中的 SQL 完成的。
所以,MyBatis 框架就抛开了 Dao 的实现类,直接定位到映射文件 mapper 中的相应 SQL 语句,对DB 进行操作。这种对 Dao 的实现方式称为 Mapper 的动态代理方式。
Mapper 动态代理方式无需程序员实现 Dao 接口。接口是由 MyBatis 结合映射文件自动生成的动态代理实现的。

Mybatis框架系列

Github项目地址