1.mybatis基础操作

一、前言

本篇将会带大家熟悉mybatis如何实现常用的增删改查。老鸟可以略过。

二、数据准备

DROP TABLE IF EXISTS student;
CREATE TABLE student (
  id INT AUTO_INCREMENT PRIMARY KEY COMMENT '学生ID',
  name VARCHAR(50) NOT NULL COMMENT '姓名',
  age INT COMMENT '年龄',
  gender TINYINT DEFAULT 0 COMMENT '性别,0|女,1|男',
  birthday DATE NOT NULL COMMENT '出生日期',
  major VARCHAR(50) COMMENT '专业',
  phone VARCHAR(100) COMMENT '电话号码',
  deleted INT DEFAULT 0 COMMENT '是否有效,0|有效,1|无效',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间'
) COMMENT='学生表';

全局配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "https://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
  <!-- 配置别名 -->xml
  <typeAliases>
    <!-- 这里typeAlias和package是有序的,要先配置typeAlias再配置package -->
    <typeAlias type="org.apache.ibatis.mytest.learntest.entity.Student" alias="student"/>
    <package name="org.apache.ibatis.mytest.learntest.entity"/>
  </typeAliases>

  <environments default="development">
    <environment id="development">
      <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?pedantic=true&amp;rewriteBatchedStatements=true&amp;allowMultiQueries=true&amp;useCursorFetch=true" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <!-- class:本地类文件 resource:磁盘路径 resource:classpath路径 url:网络路径 -->
    <!-- 注意一个类不能被扫描到多次 -->
    <mapper class="org.apache.ibatis.mytest.learntest.mapper.StudentMapper" />
<!--    <package name="org.apache.ibatis.mytest.learntest.mapper"/>-->
  </mappers>
</configuration>

这里注意节点配置的顺序, 还有mappers节点的配置, mappers节点扫描的类不能重复扫描。

细心的人应该发现了, mybatis的配置文件(mybatis-config.xml)是使用DTD文件约束的。对于xml文件定于和约束有两种方式, 分别是DTD和schema。

简单来说, DTD适合用于较为简单的 XML 文档结构定义,只有 CDATA(字符数据)、ID(唯一标识符)等基本类型

schema 提供了强类型定义, 能够精确校验元素和属性的内容类型并且支持命名空间, 更适合现代 XML 应用。

既然mybatis使用DTD文件约束, 那么它的文档结构必然是很简单的。

建表语句

DROP TABLE IF EXISTS student;
CREATE TABLE student (
  id INT AUTO_INCREMENT PRIMARY KEY COMMENT '学生ID',
  name VARCHAR(50) NOT NULL COMMENT '姓名',
  age INT COMMENT '年龄',
  gender TINYINT DEFAULT 0 COMMENT '性别,0|女,1|男',
  birthday DATE NOT NULL COMMENT '出生日期',
  major INT COMMENT '专业',
  phone VARCHAR(100) COMMENT '电话号码',
  deleted INT DEFAULT 0 COMMENT '是否有效,0|有效,1|无效',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间'
) COMMENT='学生表';

实体类定义

import java.time.LocalDate;
import java.time.LocalDateTime;

public class Student {
   

  private Integer id;

  private String name;

  private Integer age;

  private Integer gender;

  private LocalDate birthday;

  private Integer major;

  private String phone;

  private Integer deleted;

  private LocalDateTime createdAt;

  private LocalDateTime updatedAt;

  // ... 此处省略getter/setter
}

定义Mapper文件

public interface StudentMapper {
   

  int insertStudent(Student student);

}

定义StudentMapper.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.apache.ibatis.mytest.learntest.mapper.StudentMapper">

    <insert id="insertStudent">
        insert into student(name, age, gender, birthday, major, phone)
        values(#{name}, #{age}, #{gender}, #{birthday}, #{major}, #{phone})
    </insert>

</mapper>

公共方法

private SqlSessionFactory sqlSessionFactory;

  @BeforeEach
  public void setup() {
   
    try (Reader reader = Resources.getResourceAsReader("your mybatis-config.xml path")) {
   
      // DefaultSqlSessionFactory
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    } catch (IOException e) {
   
      throw new RuntimeException(e);
    }
  }

这里Resources.getResourceAsReader指定配置文件的位置即可

三、基本crud

1.insert

单条插入

@Test
  void testInsert() {
   
    // 注意openSession()方法默认是开启事务的,需要手动提交事务
    try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
   
      StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
      Student student = getStudent();
      int i = mapper.insertStudent(student);
      System.out.println("i = " + i);
    }
  }

  private Student getStudent() {
   
    Student student = new Student();
    student.setName("小乔同学");
    student.setAge(18);
    student.setGender(1);
    student.setBirthday(LocalDate.of(2000, 9, 3));
    student.setMajor(1);
    student.setPhone("13400001814");
    return student;
  }

这里注意下openSession方法, 没有指定自动提交的话, 它默认是需要手动提交的, 也就是开启了事务, 咋们测试的时候用自动提交设置autoCommit为true即可

insert into values(…),(…)

在StudentMapper.xml文件中加一个代码模块

<insert id="insertValues">
        insert into student(name, age, gender, birthday, major, phone)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.name}, #{item.age}, #{item.gender}, #{item.birthday}, #{item.major}, #{item.phone})
        </foreach>
    </insert>

在StudentMapper.java类中加入一个方法

int insertValues(List<Student> students);

再加一个测试类

@Test
  void batchInsert() {
   
    try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
   
      StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
      List<Student> students = getStudentList();
      int i = mapper.insertValues(students);
      System.out.println("i = " + i);
    }
  }

executeBatch

使用executeBatch批量插入

/**
   * executeBatch
   */
  @Test
  void insertByExecuteBatch() {
   
    try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, true)) {
   
      StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
      List<Student> students = getStudentList2();
      for (Student student : students) {
   
        int i = mapper.insertStudent(student);
        System.out.println("i = " + i);
      }
      sqlSession.flushStatements();
    }
  }

/**
 * 测试数据
 */
private List<Student> getStudentList2() {
   
    Student student1 = new Student();
    student1.setName("小黑同学");
    student1.setAge(19);
    student1.setGender(1);
    student1.setBirthday(LocalDate
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncleqiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值