一、Mybatis快速入门

mybatis-3.5.3.jar

mysql-connector-java-8.0.30.jar

1.框架

框架是一款半成品软件,我们可以基于这个半成品软件继续开放,完成我们个性化的需求

2.ORM介绍

  • ORM(Object Relational Mapping):对象关系映射
  • 指的是持久化数据和实体对象的映射模式,为了解决面向对象与关系型数据库存在的互不匹配的现象的技术。

22091801

3.原始jdbc操作

    @Override
    public Student findById(Integer sid) {
        Student student = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 注册驱动  可省
            //Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db","root","");
            // 获取执行者对象
            statement = connection.createStatement();
            // 执行sql语句 接受返回的结果集
            String sql = "select * from student where sid ="+sid;
            resultSet = statement.executeQuery(sql);
            // 处理结果集
            while (resultSet.next()) {
                Integer id = resultSet.getInt("sid");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                Date birthday = resultSet.getDate("birthday");

                student = new Student(id, name, age, birthday);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }

        return student;
    }

4. 原始jdbc操作的分析

  • 原始 JDBC 的操作问题分析

    ​ 1.频繁创建和销毁数据库的连接会造成系统资源浪费从而影响系统性能。

    1. sql 语句在代码中硬编码,如果要修改 sql 语句,就需要修改 java 代码,造成代码不易维护。
    2. 查询操作时,需要手动将结果集中的数据封装到实体对象中。
    3. 增删改查操作需要参数时,需要手动将实体对象的数据设置到 sql 语句的占位符。
  • 原始 JDBC 的操作问题解决方案

    ​ 1.使用数据库连接池初始化连接资源。

    1. 将 sql 语句抽取到配置文件中。
    2. 使用反射、内省等底层技术,将实体与表进行属性与字段的自动映射

5.什么是Mybatis

mybatis 是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。

MyBatis官网

6.Mybatis快速入门

  • 数据准备

  • 导入jar包

    • mysql-connector-java-8.0.30.jar
    • mybatis-3.5.3.jar
  • 在src下创建映射配置文件 StudentMapper

  • 在src下创建核心配置文件 MybatisConfig

  • 编写测试类完成相关api的使用

  • 测试

1)Strudent类
package com.codeui.bean;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试类

package com.codeui.test;

import com.codeui.bean.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 MybatisTest {
    @Test
    public void  selectAll(){

        try {
            //加载核心配置文件
            //MybatisTest.class.getClassLoader().getResourceAsStream()
            InputStream resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            //获取SqlSession工厂对象
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过sqlSession工厂对象获取SqlSession
            SqlSession sqlSession = build.openSession();
            //执行配置文件中的sql语句,带回结果
            List<Student> students = sqlSession.selectList("StudentMapper.selectAll");
            for (Student student : students) {
                System.out.println(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2)MybatisConfig.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="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test_db"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
3)StudentMapper.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="StudentMapper">
    <select id="selectAll" resultType="com.codeui.bean.Student">
        SELECT * from student;
    </select>
</mapper>

二、相关API

1.Resources

加载资源的工具类

2022-09-19_18-28-13

2.SqlSessionFactoryBuilder

获取 SqlSessionFactory 工厂对象的功能类

SqlSessionFactoryBuilder -> SqlSessionFactory -> sqlSession

2022-09-19_18-38-18

3.SqlSessionFactory

获取 SqlSession 构建者对象的工厂接口

22091901

4.SqlSession

构建者对象接口。用于执行 SQL、管理事务、接口代理。

2022-09-19_18-43-12

三、映射配置文件

<?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 名称空间
-->
<mapper namespace="StudentMapper">
<!-- select 查询功能的标签
             id  唯一标识符
             resultType 结果映射对象
             parameterType 指定类型映射对象类型
             -->
    <select id="selectAll" resultType="com.codeui.bean.Student">
        SELECT * from student;
    </select>
</mapper>

1.查询

<select id="selectAll" resultType="com.codeui.bean.Student" parameterType="java.lang.Integer">
    SELECT * from student where id = #{id};
</select>
public void selectById(){
    InputStream resourceAsStream = MybatisTest.class.getClassLoader().getResourceAsStream("MybatisConfig.xml");

    SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);

    SqlSession sqlSession = build.openSession();

    Student student = sqlSession.selectOne("StudentMapper.selectById",1);
    
    //释放资源
    sqlSession.close();
    resourceAsStream.close();
    
    System.out.println(student);
}

2.新增

    <insert id="insert" parameterType="com.codeui.bean.Student">
        insert into student values (#{id},#{name},#{age})
    </insert>
    public void insert() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");

        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = build.openSession();

        int insert = sqlSession.insert("StudentMapper.insert",new Student(6,"王磊",13));
        System.out.println(insert);
        sqlSession.commit();

        resourceAsStream.close();
        sqlSession.close();
    }

3.修改

    <update id="update" parameterType="com.codeui.bean.Student">
        UPDATE student SET name = #{name},age =#{age} where id =#{id}
    </update>
    @Test
    public void update() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");

        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = build.openSession();

        int insert = sqlSession.insert("StudentMapper.update",new Student(1,"王零",17));
        System.out.println(insert);
        sqlSession.commit();

        resourceAsStream.close();
        sqlSession.close();
    }

4.删除

    <delete id="delete" parameterType="java.lang.Integer">
        delete from student where id = #{id}
    </delete>
   @Test
    public void delete() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");

        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = build.openSession();

        int insert = sqlSession.insert("StudentMapper.delete",6);
        System.out.println(insert);
        sqlSession.commit();

        resourceAsStream.close();
        sqlSession.close();
    }

四、核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--Mybatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心根标签-->
<configuration>
<!--    environments 配置数据库环境 ,环境可以有多个-->
    <environments default="mysql">
        <!--配置数据库环境 id属性唯一标识符-->
        <environment id="mysql">
            <!-- transactionManager 事务管理
            type 属性采用JDBC默认事务
            -->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource 数据源 type属性 连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test_db"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
<!-- mappers 引入配置文件-->
    <mappers>
        <!-- mapper 引入指定配置文件
        resource 指定配置文件
        -->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

1.properties标签的使用

  • 在src下新建propertise文件

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test_db
    username=root
    password=
    
  • MybatisConfig中引入

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--Mybatis的DTD约束-->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration 核心根标签-->
    <configuration>
        <!--引入数据库配置文件-->
        <properties resource="jdbc.properties"/>
    <!--    environments 配置数据库环境 ,环境可以有多个-->
        <environments default="mysql">
            <!--配置数据库环境 id属性唯一标识符-->
            <environment id="mysql">
                <!-- transactionManager 事务管理
                type 属性采用JDBC默认事务
                -->
                <transactionManager type="JDBC"></transactionManager>
                <!--dataSource 数据源 type属性 连接池 -->
                <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>
    <!-- mappers 引入配置文件-->
        <mappers>
            <!-- mapper 引入指定配置文件
            resource 指定配置文件
            -->
            <mapper resource="StudentMapper.xml"/>
        </mappers>
    </configuration>
    

2.别名

  • 在MybatisConfig.xml中配置

        <typeAliases>
            <typeAlias type="com.codeui.bean.Student" alias="student"/>
        </typeAliases>
    
<?xml version="1.0" encoding="UTF-8" ?>
<!--Mybatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心根标签-->
<configuration>
    <!--引入数据库配置文件-->
    <properties resource="jdbc.properties"/>
<!--    environments 配置数据库环境 ,环境可以有多个-->
    <typeAliases>
        <typeAlias type="com.codeui.bean.Student" alias="student"/>
    </typeAliases>
    <environments default="mysql">
        <!--配置数据库环境 id属性唯一标识符-->
        <environment id="mysql">
            <!-- transactionManager 事务管理
            type 属性采用JDBC默认事务
            -->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource 数据源 type属性 连接池 -->
            <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>
<!-- mappers 引入配置文件-->
    <mappers>
        <!-- mapper 引入指定配置文件
        resource 指定配置文件
        -->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
    • 该包下的别名都为类名,且为小写

    •     <typeAliases>
      <!--        <typeAlias type="com.codeui.bean.Student" alias="student"/>-->
              <package name="com.codeui.bean"/>
          </typeAliases>
      

2022-09-19_19-56-44

五、传统方式实现Dao层

public class StudentMapperImpl implements StudentMapper {

    @Override
    public List<Student> selectAll() {
        SqlSessionFactory build = null;
        InputStream resourceAsStream = null;
        SqlSession sqlSession = null;
        List<Student> studentList = null;
        try {
            // 加载核心配置文件
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            // 获取sqlSession工厂对象
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过工厂对象获取sqlSession对象
            sqlSession = build.openSession(true);
            //执行映射文件中的sql语句,并接受结果
            studentList = sqlSession.selectList("StudentMapper.selectAll");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return studentList;
    }

    @Override
    public Student selectById(Integer id) {
        SqlSessionFactory build = null;
        InputStream resourceAsStream = null;
        SqlSession sqlSession = null;
        Student student = null;
        try {
            // 加载核心配置文件
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            // 获取sqlSession工厂对象
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过工厂对象获取sqlSession对象
            sqlSession = build.openSession(true);
            //执行映射文件中的sql语句,并接受结果
            student = sqlSession.selectOne("StudentMapper.selectById",id);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return student;
    }

    @Override
    public Integer insert(Student student) {
        SqlSessionFactory build = null;
        InputStream resourceAsStream = null;
        SqlSession sqlSession = null;
        Integer result = null ;
        try {
            // 加载核心配置文件
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            // 获取sqlSession工厂对象
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过工厂对象获取sqlSession对象
            sqlSession = build.openSession(true);
            //执行映射文件中的sql语句,并接受结果
            result = sqlSession.insert("StudentMapper.insert",student);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }

    @Override
    public Integer update(Student student) {
        SqlSessionFactory build = null;
        InputStream resourceAsStream = null;
        SqlSession sqlSession = null;
        Integer result = null ;
        try {
            // 加载核心配置文件
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            // 获取sqlSession工厂对象
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过工厂对象获取sqlSession对象
            sqlSession = build.openSession(true);
            //执行映射文件中的sql语句,并接受结果
            result = sqlSession.update("StudentMapper.update",student);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }

    @Override
    public Integer delete(Integer id) {
        SqlSessionFactory build = null;
        InputStream resourceAsStream = null;
        SqlSession sqlSession = null;
        Integer result = null ;
        try {
            // 加载核心配置文件
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
            // 获取sqlSession工厂对象
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过工厂对象获取sqlSession对象
            sqlSession = build.openSession(true);
            //执行映射文件中的sql语句,并接受结果
            result = sqlSession.delete("StudentMapper.delete",id);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }
}

1.log4j

  • 导包

    • log4j-1.2.17.jar
  • 修改核心配置文件

    • <settings>
          <setting name="logImpl" value="log4j"/>
      </settings>
      
<?xml version="1.0" encoding="UTF-8" ?>
<!--Mybatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心根标签-->
<configuration>

    <!--引入数据库配置文件-->
    <properties resource="jdbc.properties"/>

    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
<!--    environments 配置数据库环境 ,环境可以有多个-->
    <typeAliases>
<!--        <typeAlias type="com.codeui.bean.Student" alias="student"/>-->
        <package name="com.codeui.bean"/>
    </typeAliases>
    <environments default="mysql">

        <!--配置数据库环境 id属性唯一标识符-->
        <environment id="mysql">
            <!-- transactionManager 事务管理
            type 属性采用JDBC默认事务
            -->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource 数据源 type属性 连接池 -->
            <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>
<!-- mappers 引入配置文件-->
    <mappers>
        <!-- mapper 引入指定配置文件
        resource 指定配置文件
        -->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
  • src下创建配置文件log4j.properties

    • # Global logging configuration
      log4j.rootLogger=DEBUG, stdout
      # Console output...
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n