Day_01 MyBatis

本文详细讲解了分模块工程构建、Maven父项目管理、DAO与Service模块设计,以及MyBatis从基础到高级应用,包括JDBC问题、MyBatis入门、映射文件、操作用户等,适合深入理解数据库操作与持久层框架。
摘要由CSDN通过智能技术生成

01-分模块构建工程(掌握)

  • 为什么?
    • ①如果所有的功能都在一个项目中,单一功能的用户量增加,去做服务器集群,会导致服务器性能浪费;
    • ②如果将不同功能分配到不同项目中,会发现会有一些重复代码;
    • 基于以上两点因素,考虑使用分模块构建工程。

02-聚合项目之maven-parent(掌握)

  • 开发步骤

    • ①创建项目
      • 不需要骨架
      • 打包方式=pom
      • 版本锁定
  • 代码实现

    <groupId>com.panghu</groupId>
    <artifactId>maven-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    
    <properties>
        <junit.version>4.13.2</junit.version>
        <mysql.version>5.1.48</mysql.version>
        <druid.version>1.2.8</druid.version>
        <dbutils.version>1.7</dbutils.version>
        <servlet.version>4.0.1</servlet.version>
        <jsp.version>2.3.3</jsp.version>
        <beanutils.version>1.9.4</beanutils.version>
        <lombok.version>1.18.20</lombok.version>
        <thymeleaf.version>3.0.12.RELEASE</thymeleaf.version>
    </properties>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-dbutils</groupId>
                <artifactId>commons-dbutils</artifactId>
                <version>${dbutils.version}</version>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet.version}</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>${jsp.version}</version>
            </dependency>
    
            <dependency>
                <groupId>commons-beanutils</groupId>
                <artifactId>commons-beanutils</artifactId>
                <version>${beanutils.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf</artifactId>
                <version>${thymeleaf.version}</version>
            </dependency>
    
        </dependencies>
    </dependencyManagement>
    

03-聚合项目之dao模块(掌握)

  • 开发步骤

    • ①创建模块
      • 以maven-parent为父工程
      • 不选择骨架
    • ②编写pom.xml
      • 打包方式=jar
      • 依赖管理
    • ③定义dao接口及其实现子类
  • ①创建模块

  • ②编写pom.xml

    <!--继承-->
    <parent>
        <artifactId>maven-parent</artifactId>
        <groupId>com.panghu</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    
    <artifactId>maven-dao</artifactId>
    <packaging>jar</packaging>
    
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
    
    </dependencies>
    
  • ③定义dao接口及其实现子类

    public class BookDaoImpl extends BaseDao<Book> implements BookDao {
        public List<Book> selectBookList() throws Exception {
            return selectAll(
                    Book.class,
                    "select book_id bookId , book_name bookName , author,price,sales,stock,img_path imgPath from t_book"
            );
        }
    }
    

04-聚合项目之service模块(掌握)

  • 开发步骤

    • ①创建模块
      • 以maven-parent为父工程
      • 不选择骨架
    • ②编写pom.xml
      • 打包方式=jar
      • 依赖管理
      • 依赖maven-dao
    • ③定义service接口及其实现子类
  • ①创建模块

  • ②编写pom.xml

    <parent>
        <artifactId>maven-parent</artifactId>
        <groupId>com.panghu</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    
    <artifactId>maven-service</artifactId>
    <packaging>jar</packaging>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  • ③定义service接口及其实现子类

    public class BookServiceImpl implements BookService {
        @Override
        public List<Book> selectBookList() throws Exception {
            BookDao bookDao = new BookDaoImpl();
            return bookDao.selectBookList();
        }
    }
    

05-聚合项目之controller模块(掌握)

  • ①创建模块

    • ①maven-parent为父工程
    • ②选择maven-archetype-webapp模块
  • ②编写pom.xml

    • 打包方式=war
    • 依赖管理
    • 依赖maven-service模块
  • ③编写BookController

  • ④编写book-list.html

  • ①创建模块

  • ②编写pom.xml

    <parent>
        <artifactId>maven-parent</artifactId>
        <groupId>com.panghu</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    
    <artifactId>maven-controller</artifactId>
    <packaging>war</packaging>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
        </dependency>
    
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
        </dependency>
    
        <dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>maven-service</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>
    
    </dependencies>
    
  • ③编写BookController

    @WebServlet("/book")
    public class BookController extends ModelBaseServlet {
    
    
        public void selectBookList(HttpServletRequest request, HttpServletResponse response) {
            BookService bookService = new BookServiceImpl();
            try {
                List<Book> bookList = bookService.selectBookList();
                request.setAttribute("bookList", bookList);
                processTemplate("book-list", request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
  • ④编写book-list.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>图书列表</title>
    </head>
    <body>
    
    
    <ul>
    
        <li th:each="book : ${bookList}" th:text="${book.bookName}"></li>
    
    </ul>
    
    </body>
    </html>
    

06-原始JDBC存在的问题(掌握)

  • 代码实现

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        //1,引入依赖
        //2,加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //3,获取链接
         connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day50?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "root");
        //4,获取执行sql对象
         statement = connection.prepareStatement("select * from tb_user where id = ?");
        statement.setInt(1,1);
        //5,编写sql,执行sql
         resultSet = statement.executeQuery();
        //6,处理结果集
        User user = null;
        while (resultSet.next()) {
            user = new User(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3));
        }
        System.out.println(user);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //7,释放资源
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
    
            connection = null;
        }
    
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
    
            resultSet = null;
        }
    
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
    
            statement = null;
        }
    }
    
  • 存在问题

    • ①driverClassName、jdbcUrl、username、password、sql语句存在字符串硬编码
    • ②频繁地创建和销毁Connection对象
    • ③手动地处理输入映射(给占位符?赋值)
    • ④手动地处理输出映射(将结果集处理成java数据)
    • ⑤手动地释放资源
  • 解决方案

    • ①将driverClassName、jdbcUrl、username、password、sql语句存放到配置文件中
    • ②使用连接池
    • ③使用反射 + 内省(default)操作
    • ④使用反射 + 内省(default)操作
    • ⑤内省(default)操作

07-MyBatis概述(掌握)

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

08-MyBatis入门案例(掌握)

  • 开发步骤

    • ①引入mybatis的依赖
    • ②编写mybatis-config.xml
      • 配置事务管理器
      • 配置数据源
      • 加载mapper映射配置文件
    • ③编写mapper1.xml
      • 配置statement
    • ④定义dao接口及其实现子类
      • 创建SqlSessionFactory对象
      • 获取SqlSession对象
      • 执行指定的Statement
      • 释放资源
    • ⑤代码测试
  • ①引入mybatis的依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    
    </dependencies>
    
    
  • ②编写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/mydb1"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    
    
        <mappers>
            <mapper resource="mapper1.xml"/>
        </mappers>
    
    
    </configuration>
    
    
  • ③编写mapper1.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="test">
    
    
        <!--
            需求:根据id查询用户信息
            配置Statement
            id : 唯一表示
            parameterType : 输入映射
            resultType : 输出映射
        -->
        <select id="selectUserById" parameterType="int" resultType="com.panghu.pojo.User">
            select * from t_user where userId = #{userId}
        </select>
    
    
    </mapper>
    
    
  • ④定义dao接口及其实现子类

    public class UserDaoImpl implements UserDao {
    
    
        public User selectUserById(Integer userId) throws Exception {
            //①创建SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③执行指定的Statement
            User user = sqlSession.selectOne("test2.selectUserById", userId);
            //④释放资源
            sqlSession.close();
            return user;
        }
    
    
    }
    
    
  • ⑤代码测试

    public class UserDaoTest {
    
        @Test
        public void selectUserById() throws Exception {
            UserDao userDao = new UserDaoImpl();
            User user = userDao.selectUserById(1);
            System.out.println("user = " + user);
        }
    }
    
    

09-mapper映射文件说明(掌握)

  • 映射文件
    • image-20220322113405925

10-添加用户(掌握)

  • 代码实现

    <insert id="addUser" parameterType="com.atguigu.pojo.User">
        insert into t_user values(null,#{userName},#{userPwd},#{money},#{address})
    </insert>
    
    
    public int addUser(User inputUser) throws Exception {
        //①创建SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //②获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //③执行指定的Statement
        int addUser = sqlSession.insert("addUser", inputUser);
        sqlSession.commit();
        sqlSession.close();
        return addUser;
    }
    
    

11-删除用户(掌握)

  • 代码实现

    <delete id="deleteUserById" parameterType="int">
        delete from t_user where userId=#{userId}
    </delete>
    
    
    public int deleteUserById(Integer userId) throws Exception {
        //①创建SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //②获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //③执行指定的Statement
        int deleteUserById = sqlSession.delete("deleteUserById", userId);
        sqlSession.commit();
        sqlSession.close();
        return deleteUserById;
    }
    
    

12-修改用户(掌握)

  • 代码实现

    <update id="updateUserById" parameterType="com.panghu.pojo.User">
        update t_user set
        userName = #{userName} , userPwd = #{userPwd},money = #{money},address=#{address}
        where userId=#{userId}
    </update>
    
    public int updateUserById(User inputUser) throws Exception {
        //①创建SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //②获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //③执行指定的Statement
        int updateUserById = sqlSession.update("updateUserById", inputUser);
        sqlSession.commit();
        sqlSession.close();
        return updateUserById;
    }
    

13-Resources类概述(掌握)

  • 概述
    • 用于加载mybatis核心配置文件,获取对应的输入流。
    • 之前的用法没有问题。

14-SqlSessionFactoryBuilder类概述(掌握)

  • 概述
    • 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 最好是匿名对象。
    • 用于获取SqlSessionFactory对象
    • 之前的用法没有问题。

15-SqlSessionFactory接口概述(掌握)

  • 概述
    • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。
    • 用于获取SqlSession对象
    • 之前的用法有问题。

16-SqlSession接口概述(掌握)

  • 概述
    • 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
    • 之前的用法没有问题。
  • 作用
    • ①执行指定Statement
    • ②事务管理
    • ③获取dao接口的代理对象

17-mybatis的传统dao开发(掌握)

  • 概述

    • mybatis操作数据库有两种开发模式:①传统dao开发、②mapper接口代理开发
  • ①传统dao开发

    • dao接口 + dao实现子类 + mapper映射文件
  • ②mapper接口代理开发

    • dao接口 + mapper映射文件
  • 代码实现

    public class UserDaoImpl implements UserDao {
    
        private SqlSessionFactory sqlSessionFactory;//后续由Spring框架提供一个单例的SqlSessionFactory对象
    
        public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
            this.sqlSessionFactory = sqlSessionFactory;
        }
    
        public User selectUserById(Integer userId) throws Exception {
            //①创建SqlSessionFactory对象
    
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③执行指定的Statement
            User user = sqlSession.selectOne("test.selectUserById", userId);
            //④释放资源
            sqlSession.close();
            return user;
        }
    
        public int addUser(User inputUser) throws Exception {
            //①创建SqlSessionFactory对象
    
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③执行指定的Statement
            int addUser = sqlSession.insert("addUser", inputUser);
            sqlSession.commit();
            sqlSession.close();
            return addUser;
        }
    
        public int deleteUserById(Integer userId) throws Exception {
            //①创建SqlSessionFactory对象
    
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③执行指定的Statement
            int deleteUserById = sqlSession.delete("deleteUserById", userId);
            sqlSession.commit();
            sqlSession.close();
            return deleteUserById;
        }
    
        public int updateUserById(User inputUser) throws Exception {
            //①创建SqlSessionFactory对象
    
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③执行指定的Statement
            int updateUserById = sqlSession.update("updateUserById", inputUser);
            sqlSession.commit();
            sqlSession.close();
            return updateUserById;
        }
    
    
    }
    
    
    public class UserDaoTest {
    
        private SqlSessionFactory sqlSessionFactory;
    
    
        @Before
        public void init() throws IOException {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        }
    
        @Test
        public void selectUserById() throws Exception {
            UserDao userDao = new UserDaoImpl(sqlSessionFactory);
            User user = userDao.selectUserById(1);
            System.out.println("user = " + user);
        }
    
        @Test
        public void addUser() throws Exception {
            UserDao userDao = new UserDaoImpl(sqlSessionFactory);
            int addUser = userDao.addUser(new User(null, "xiaoqiu", "xiaoqiu", 10000.0, "武汉市"));
            System.out.println("addUser = " + addUser);
        }
    
        @Test
        public void deleteUserById() throws Exception {
            UserDao userDao = new UserDaoImpl(sqlSessionFactory);
            int deleteUserById = userDao.deleteUserById(6);
            System.out.println("deleteUserById = " + deleteUserById);
        }
    
        @Test
        public void updateUserById() throws Exception {
            UserDao userDao = new UserDaoImpl(sqlSessionFactory);
            int updateUserById = userDao.updateUserById(new User(5, "a", "a", 20000.0, "武汉市"));
            System.out.println("updateUserById = " + updateUserById);
        }
    }
    
    
  • 存在问题

    • ①dao实现子类多了之后难以维护;
    • ②dao实现子类和mapper映射文件存在耦合。

18-mybatis的mapper接口代理开发(掌握)

  • 概述

    • dao接口 + mapper映射文件
  • 开发步骤

    • ①mapper映射文件存放到dao接口相同的目录
    • ②mapper映射文件名称和dao接口名称相同
    • ③namespace和dao接口的全限定类名相同
    • ④id和dao接口的方法名相同
    • ⑤parameterType和dao接口的形参类型相同
    • ⑥resultType和dao接口的返回值类型相同
  • 代码实现

    <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/mydb1"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    
    <mappers>
        <mapper resource="com/panghu/dao/UserDao.xml"/>
    </mappers>
    
    public interface UserDao {
    
        User selectUserById(Integer userId) throws Exception;
    
        int addUser(User inputUser) throws Exception;
    
        int deleteUserById(Integer userId) throws Exception;
    
        int updateUserById(User inputUser) throws Exception;
    
    }
    
    
    <?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.atguigu.dao.UserDao">
    
    
        <select id="selectUserById" parameterType="int" resultType="com.panghu.pojo.User">
            select * from t_user where userId = #{userId}
        </select>
    
    
        <insert id="addUser" parameterType="com.panghu.pojo.User">
            insert into t_user values(null,#{userName},#{userPwd},#{money},#{address})
        </insert>
    
        <delete id="deleteUserById" parameterType="int">
            delete from t_user where userId=#{userId}
        </delete>
    
        <update id="updateUserById" parameterType="com.panghu.pojo.User">
            update t_user set
            userName = #{userName} , userPwd = #{userPwd},money = #{money},address=#{address}
            where userId=#{userId}
        </update>
    
    </mapper>
    
    
    public class UserDaoTest {
    
        @Test
        public void selectUserById() throws Exception {
            //①获取SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(
                    Resources.getResourceAsReader("mybatis-config.xml"));
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③获取UserDao代理对象
            UserDao userDao = sqlSession.getMapper(UserDao.class);
    
            User user = userDao.selectUserById(1);
            System.out.println("user = " + user);
    
            sqlSession.close();
    
    
        }
    
        @Test
        public void addUser() throws Exception {
    
            //①获取SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(
                    Resources.getResourceAsReader("mybatis-config.xml"));
            //②获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //③获取UserDao代理对象
            UserDao userDao = sqlSession.getMapper(UserDao.class);
    
            int addUser = userDao.addUser(new User(null, "zhongqiu", "zhongqiu", 10000.0, "aaa"));
            System.out.println("addUser = " + addUser);
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void deleteUserById() {
        }
    
        @Test
        public void updateUserById() {
        }
    }
    
    

19-核心配置文件解释(掌握)

  • 核心配置文件
    • image-20220322151933805
  • 常用属性
    • properties
    • settings
    • typeAliases
    • plugins
    • enviroments
    • mappers

20-mybatis内置连接池(了解)

  • 内置连接池
    • image-20220322152137218
    • jndi
      • JndiDataSourceFactory
    • pooled : 使用连接池
      • PooledDataSource
    • unpooled : 不使用连接池
      • UnpooledDataSource

21-environments标签(了解)

  • 概述

    • 配置事务管理器、数据源
  • 代码实现

    <environments default="development2">
        <!--有事务管理,不使用连接池-->
        <environment id="development">
            <!--事务管理器-->
            <transactionManager type="JDBC"/>
            <!--数据源-->
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb1"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    
        <!--有事务管理,使用连接池-->
        <environment id="development2">
            <!--事务管理器-->
            <transactionManager type="JDBC"/>
            <!--数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb1"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    
  • 注意事项

    • 如果和Spring框架整合,environments标签就不需要了。

22-properties标签(掌握)

  • 概述

    • 在mybatis中声明变量并复用。
  • 代码实现1

    <properties>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb1"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>
    
    <!---->
    <environments default="development">
        <!--有事务管理,不使用连接池-->
        <environment id="development">
            <!--事务管理器-->
            <transactionManager type="JDBC"/>
            <!--数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    
    
    </environments>
    
    
  • 代码实现2

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mydb1
    username=root
    password=root
    
    
    <properties resource="jdbc.properties"></properties>
    
    <!---->
    <environments default="development">
        <!--有事务管理,不使用连接池-->
        <environment id="development">
            <!--事务管理器-->
            <transactionManager type="JDBC"/>
            <!--数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    
    

23-settings标签之log4j(掌握)

  • 概述

    • 在开发过程中,排查问题时难免需要输出MyBatis真正执行的SQL语句、参数、结果等信息,我 们就可以借助log4j来实现执行信息的输出
  • 开发步骤

    • ①引入log4j的依赖
    • ②编写mybatis-config.xml
      • 配置settings
    • ③编写log4j.xml
  • ①引入log4j的依赖

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    
  • ②编写mybatis-config.xml

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
    
  • ③编写log4j.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
        <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
            <param name="Encoding" value="UTF-8"/>
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n"/>
            </layout>
        </appender>
    
        <logger name="java.sql">
            <level value="debug"/>
        </logger>
    
        <logger name="org.apache.ibatis">
            <level value="info"/>
        </logger>
    
        <root>
            <level value="debug"/>
            <appender-ref ref="STDOUT"/>
        </root>
    </log4j:configuration>
    
    

24-typeAliases标签(掌握)

  • 概述

    • 类型别名可为 Java 类型设置一个缩写名字。
  • 代码实现1

    <typeAliases>
        <typeAlias type="com.panghu.pojo.User" alias="user"></typeAlias>
    
    </typeAliases>
    
    
  • 代码实现2

    <typeAliases>
        <package name="com.panghu.pojo"/>
    </typeAliases>
    
    
  • 内置别名

    • image-20220322154356117
    • image-20220322154411105

25-mappers标签(掌握)

  • 概述

    • 加载mapper映射文件。
  • 代码实现1(推荐)

    <mappers>
    
        <!--适用于传统dao开发,也适用于mapper接口代理开发-->
        <mapper resource="com/panghu/dao/UserDao.xml"/>
    </mappers>
    
    
  • 代码实现2

    <mappers>
    
        <!--只适用于mapper接口代理开发-->
        <mapper class="com.panghu.dao.UserDao"></mapper>
    
    
    </mappers>
    
    
  • 代码实现3(推荐)

    <mappers>
    
        <!--只适用于mapper接口代理开发-->
        <package name="com.panghu.dao"/>
    
    </mappers>
    
    

26-plugins之分页插件(掌握)

  • 开发步骤

    • ①引入pagehelper的依赖
    • ②编写mybatis-config.xml
      • 配置PageInterceptor拦截器
    • ③编写UserService
      • 开启分页查询
    • ④代码测试
  • ①引入pagehelper的依赖

    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.3.0</version>
    </dependency>
    
    
  • ②编写mybatis-config.xml

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="reasonable" value="true"/>
        </plugin>
        
    </plugins>
    
    
  • ③编写UserService

    public class UserServiceImpl implements UserService {
    
    
        public PageInfo<User> selectUserListByPage(Integer currentPage, Integer pageSize) throws Exception {
            //开启执行分页查询
            PageHelper.startPage(currentPage, pageSize);
    
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(
                    Resources.getResourceAsReader("mybatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.selectUserList();
            sqlSession.close();
            return new PageInfo<User>(userList);
    
        }
    }
    
    
  • ④代码测试

    @Test
    public void selectUserListByPage() throws Exception {
        UserService userService = new UserServiceImpl();
        PageInfo<User> pageInfo = userService.selectUserListByPage(1, 2);
        System.out.println("pageInfo = " + pageInfo);
        System.out.println("当前页数 : " + pageInfo.getPageNum());
        System.out.println("总页数 : " + pageInfo.getPages());
        System.out.println("总记录数 : " + pageInfo.getTotal());
        System.out.println("当前页数据 : " + pageInfo.getList());
        System.out.println("每页记录数 : " + pageInfo.getPageSize());
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值