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;
      }
    }
    
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容