1. mybatis环境搭建与增删改查

开发环境

  1. IDE: Eclipse

  2. 数据库: Mysql 5.7

  3. 数据库连接工具:DBeaver

步骤

  1. 新建maven工程,命名为learnMybaits

  2. 在pom.xml中引入mybatis、 mysql驱动和Junit的依赖

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.auuid</groupId>
        <artifactId>mybatis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.6</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </project>
    
  3. 新建一个Employee类,新建一张employee表

    Employee类

    package com.auuid.bean;
    
    public class Employee {
    
      private Integer id;
      private String name;
      private Integer 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;
      }
    }
    
    

    employee表

    CREATE TABLE employee (
      id INT PRIMARY KEY AUTO_INCREMENT,
      name VARCHAR(255),
      age SMALLINT
    )
    
  4. 新建EmployeeMapper接口

    package com.auuid.dao;
    
    import com.auuid.bean.Employee;
    
    public interface EmployeeMapper {
      public Employee getById(Integer id);
      public void save(Employee employee);
      public void update(Employee employee);
      public void deleteById(Integer id);
    }
    
  5. 新建配置文件EmployeeMapper.xml和mybatis-config.xml

    EmployeeMapper.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必须是EmployeeMapper类的全类名 -->
    <!-- select 标签的id属性必须是EmployeeMapper类的方法名 -->
    <mapper namespace="com.auuid.dao.EmployeeMapper">
       <!-- resultType 是返回值的全类名 -->
       <select id="getById" resultType="com.auuid.bean.Employee">
           select * from employee where id = #{id}
       </select>
       <!-- useGeneratedKeys: 使用数据库生成的key
            keyProperty: 指定这个key赋给Employee对象的那个字段
        -->
       <insert id="save" useGeneratedKeys="true" keyProperty="id">
           insert into employee(name, age) values(#{name}, #{age})
       </insert>
       <update id="update">
           update employee set name=#{name}, age=#{age} where id=#{id}
       </update>
       <delete id="deleteById">
           delete from employee where id=#{id}
       </delete>
    </mapper>
    

    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.cj.jdbc.Driver" />
                   <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&amp;useSSL=false" />
                   <property name="username" value="root" />
                   <property name="password" value="123456" />
               </dataSource>
           </environment>
       </environments>
       <mappers>
           <mapper resource="EmployeeMapper.xml" />
       </mappers>
    </configuration>
    
  6. 新建测试类EmployeeTestCase

    package com.auuid;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Random;
    import java.util.UUID;
    
    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 com.auuid.bean.Employee;
    import com.auuid.dao.EmployeeMapper;
    
    public class EmployeeTestCase {
      
      @Test
      public void save() throws IOException {
        SqlSession openSession = null;
        
        try {
          openSession = openSession();
          EmployeeMapper employeeMapper = openSession.getMapper(EmployeeMapper.class); //生产接口代理对象
          employeeMapper.save(newEmployee());
          openSession.commit();
        } finally {
          openSession.close();
        }
      }
      
      private SqlSession openSession() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //读取数据源
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //构建sessionFactory
        SqlSession openSession = sqlSessionFactory.openSession(); //构建session
        return openSession;
      }
      
      private Employee newEmployee() {
        Employee employee = new Employee();
        employee.setName(UUID.randomUUID().toString());
        employee.setAge(new Random().nextInt(100));
        return employee;
      }
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容