MyBatis 入门

创建MyBatis项目

搭建环境

创建 MySQL 数据库,表,并且插入数据。这里我们创建两张表,student 表和 teacher 表。

#创建数据库
CREATE DATABASE mybatis;

#创建教师表
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

#创建学生表
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

插入数据

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'),(2,'张老师');


INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '2');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '2');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

新建项目

这里使用的是 IntelliJ IDEA

  • 选择 Maven 项目,点下一步

    iAUZS2R1u8.png!large
  • 填写 GroupId 和 ArtifactId

    ILy67kT45F.png!large
  • 项目名为 Mybatis_Study

    AnWwigSD7f.png!large
  • 导入依赖

    <!--防止3 字节的 UTF-8 序列的字节 3 无效的问题-->
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>8.0.20</version>
          </dependency>
    
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.5.2</version>
          </dependency>
    
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.12</version>
          </dependency>
      </dependencies>
    
      <!--在 build 中配置 resources ,来防止我们资源导出失败的问题-->
      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
              <resource>
                  <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
          </resources>
      </build>
  • 项目结构

    2Tu0munERY.png!large
  • mybatis-config.xml 配置文件和 db.properties 外部资源文件

    <?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>
    
      <!--引入外部配置文件-->
      <properties resource="db.properties"/>
    
      <settings>
          <!--标准的日志工厂实现-->
          <setting name="logImpl" value="STDOUT_LOGGING"/>
      </settings>
    <!--可以给实体类起别名-->
      <typeAliases>
          <typeAlias type="com.hudu.pojo.Student" alias="Student"/>
          <typeAlias type="com.hudu.pojo.Teacher" alias="Teacher"/>
          <!--扫描实体类的包,它的默认别名就为这个类的类名,实体类比较多用package扫描-->
          <!--<package name="com.com.test.pojo"/>-->
      </typeAliases>
    
      <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>
    
      <mappers>
          <mapper resource="com/hudu/dao/TeacherMapper.xml"/>
          <mapper resource="com/hudu/dao/StudentMapper.xml"/>
          <!-- <mapper class="com.hudu.dao.TeacherMapper"/>-->
          <!-- <mapper class="com.hudu.dao.StudentMapper"/>-->
          <!-- <package name="com.hudu.dao"/>-->
      </mappers>
    </configuration>
#db.properties文件
#注意 mysql 8.0 之后 driver 为 com.mysql.cj.jdbc.Driver
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=数据库用户名
password=数据库密码

代码编写

上面从环境到项目结构到基础配置都已经完成,下面开始真正使用 MyBatis

MybatisUtil 工具类

此类主要简化之后的代码编写,将重复使用的创建 SqlSession 的过程封装成一个工具类,便于之后的调用使用。

  • MybatisUtil

    public class MybatisUtil {
      private static SqlSessionFactory sqlSessionFactory;
    
      static {
          try {
              String resource = "mybatis-config.xml";
              InputStream inputStream = Resources.getResourceAsStream(resource);
              sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
    
      public static SqlSession getSqlSession() {
          //true 表示事务自动提交
          return sqlSessionFactory.openSession(true);
      }
    }
  • 实体类编写

    //这部分主要展示实体类属性
    public class Student {
    private int id;
    private String name;
    private int tid;
    }
    public class Teacher {
    private int id;
    private String name;
    //一个老师对应多个学生,也可在学生类中多对一关系,将 int tid 改为 Teacher teacher 属性
    private List<Student> students;
    }
  • 简单要求:获取所有学生信息

    //编写 StudentMapper 接口中的方法
    public interface StudentMapper {
    List<Student> getStudents();
    }
  • 对应的 StudentMapper.xml 文件编写

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.hudu.dao.StudentMapper">
      <select id="getStudents" resultType="Student">
          select * from student
      </select>
    </mapper>
  • 测试类

    @Test
      public void test1() {
          SqlSession sqlSession = MybatisUtil.getSqlSession();
          StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
          List<Student> students = mapper.getStudents();
          for (Student student : students) {
              System.out.println(student);
          }
          sqlSession.close();
      }

总结

至此,一个简单的使用 MyBatis 对数据库进行查询操作的 Deemo 已经完成,之后会讲 MyBatis 的原理及各种用法。

使用 MyBasit 的具体流程如下:

  • 导入依赖,注意字符集及资源导出失败的问题
  • 配置 mybatis-config.xml 配置文件,需要可以引入外部配置文件
  • 根据 MySQL 表中字段名和属性编写实体类
  • 创建实体类的 Mapper 接口
  • 创建接口关联的 Mapper.xml 文件,绑定接口,编写 SQL 语句
  • 在 MyBatis.xml 文件中添加 resource Mapper.xml 文件或者 对应Mapper 类。
  • 编写测试代码测试
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
247
粉丝
17
喜欢
213
收藏
58
排名:732
访问:9674
私信
所有博文
社区赞助商