开始

  1. 准备MySQL数据库

    CREATE DATABASE `mybatis`;
    USE `mybatis`;
    CREATE TABLE `user` ( 
        `id` INT ( 20 ) PRIMARY KEY, 
        `name` VARCHAR ( 30 ) DEFAULT NULL, 
        `pwd` VARCHAR ( 30 ) DEFAULT NULL 
    ) ENGINE = INNODB DEFAULT CHARSET = utf8;
    
    INSERT INTO `user` ( `id`, `name`, `pwd` )
    VALUES
        ( 1, "张三", "123456" ),
        ( 2, "李四", "123123" ),
        ( 3, "王五", "111111" )
    
  2. 创建Maven项目导入依赖

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.25</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
    </dependency>
    
  3. 编写MyBatis配置文件

    /resources/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核心配置文件-->
    <configuration>
        <!--引入配置文件,实现参数外部动态配置-->
        <!--resource路径前面不能加/-->
        <properties resource="db.properties"></properties>
        <environments default="development">
            <!--可以搭建多套环境-->
            <environment id="development">
                <transactionManager type="JDBC"/>
                <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>
        <!--添加mapper映射,包名以路径形式,最前面不加/-->
        <mappers>
            <mapper resource="org/gs/mapper/user/UserMapper.xml"/>
        </mappers>
    </configuration>
    
  4. 编写MySQL配置文件

    /resources/db.properties

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
    username=root
    password=root
    
  5. 编写mybatis工具类

    package com.gs.utils;
    
    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 java.io.IOException;
    import java.io.InputStream;
    
    /**
     * MyBatis工具类
     * @author admin
     * @date 2021/9/10 5:04 下午
     */
    public class MyBatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            // 第一步:获取sqlSessionFactory对象
            try {
                String resource = "mybatis-config.xml";
                InputStream resourceAsStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        // 利用SqlSessionFactory获得SqlSession的实例
        // SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
        public static SqlSession getSqlsession() {
            // 此处可以传递一个布尔值,如果布尔值为true,则关闭事物并开启自动提交,默认为false
            return sqlSessionFactory.openSession();
        }
    }
    
  6. 编写代码

    1. 实体类

      package com.gs.pojo;
      
      /**
       * @author admin
       * @date 2021/9/10 5:19 下午
       */
      public class User {
          private int id;
          private String name;
          private String pwd;
      
          public User() {
          }
      
          public User(int id, String name, String pwd) {
              this.id = id;
              this.name = name;
              this.pwd = pwd;
          }
      
          public int getId() {
              return id;
          }
      
          public void setId(int id) {
              this.id = id;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public String getPwd() {
              return pwd;
          }
      
          public void setPwd(String pwd) {
              this.pwd = pwd;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "id=" + id +
                      ", name='" + name + '\'' +
                      ", pwd='" + pwd + '\'' +
                      '}';
          }
      }
      
    2. Dao接口

      package org.gs.mapper.user;
      
      import org.gs.pojo.User;
      import java.util.List;
      
      /**
       * @author admin
       * @date 2021/9/10 5:21 下午
       */
      public interface UserMapper {
      
          List<User> getUserList();
      
      }
      
    3. 接口实现类,由原来的Java文件转换为一个Mapper配置文件

      UserMapperImpl.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">
      <!--namespace=绑定一个对应的Dao/Mapper接口-->
      <mapper namespace="org.gs.mapper.user.UserMapper">
          <!--select语句-->
          <select id="getUserList" resultType="org.gs.pojo.User">
              select *
              from user;
          </select>
      </mapper>
      
    4. Junit进行测试

      package org.gs.mapper;
      
      import org.apache.ibatis.session.SqlSession;
      import org.gs.mapper.user.UserMapper;
      import org.gs.pojo.User;
      import org.gs.utils.MyBatisUtils;
      import org.junit.Test;
      
      import java.util.List;
      
      /**
       * @author admin
       * @date 2021/9/10 5:41 下午
       */
      public class UserMapperTest {
      
          @Test
          public void test() {
              // 1. 获得SqlSession对象
              SqlSession sqlSession = null;
      
              try {
                  sqlSession = MyBatisUtils.getSqlsession();
                  // 2. 执行SQL
                  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                  List<User> userList = mapper.getUserList();
                  for (User user : userList) {
                      System.out.println(user);
                  }
              } finally {
                  sqlSession.close();
              }
          }
      
      }
      
      image-20210910181237135
      Image
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:52

results matching ""

    No results matching ""