Java MyBatis Getting Started Tutorial

1. MyBatis

MyBatis is a java-based persistence layer ORM (Object Relational Mapping)

The framework encapsulates jdbc internally. Developers only need to focus on the SQL statement itself, and do not need to deal with complicated processes such as loading drivers, creating connections, creating statements, closing connections, and resources.

MyBatis configures various sql statements to be executed through xml or annotations, and generates the final executed sql statement through mapping between java objects and sql dynamic parameters. Finally, the mybatis framework executes sql and maps the results to java objects. and return.

1. Code that does not use MyBatis

(1) Register driver

(2) Get connection

(3) Obtain the database operation object

(4) Execute SQL statements

(5) Process the query result set

(6) Release resources

These lead to

(1) There is a lot of code and low development efficiency

(2) Need to pay attention to the creation and destruction of Connection, Statement, 9ResultSet objects

(3) The results of ResultSet query need to be encapsulated as List by yourself

(4) There are more repeated codes

(5) Business code and database operations are mixed together.

 String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/mydb";
        String user = "root";
        String pwd = "123456";
 
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            //1、注册驱动(连接的数据库)
            Class.forName(driver);
 
            //2、获取连接
            conn = DriverManager.getConnection(url,user,pwd);
 
            //3、获取数据库操作对象(专门执行sql语句的对象)
            stmt = conn.createStatement();
 
            //4、执行SQL语句(DQL DML....)
            String sql = "select empno,empname as name,sal from emp2 where empno=7369";
            rs = stmt.executeQuery(sql);
 
            //5、处理查询结果集(只有当第四步执行的是select语句的时候,才有处理查询结果集)
            while (rs.next()){
                /*
                (1)下标取值;下标从 1 开始
                */
                String empno = rs.getString(1);
                String empname = rs.getString(2);
                String sal = rs.getString(3);
                System.out.println(empno + " " + empname + " " + sal);
 
                /*
                (2)数据类型取值
                */
                int empno1 = rs.getInt(1);
                String empname1 = rs.getString(2);
                Double sal1 = rs.getDouble(3);
                System.out.println(empno1 + " " + empname1 + " " + sal1);
 
                /*
                (3)字段名取值
                */
                String empno2 = rs.getString("empno");
                //如果执行的SQL语句中有别名,需要使用别名字段取值
                String empname2 = rs.getString("name");
                String sal2 = rs.getString("sal");
                System.out.println(empno2 + " " + empname2 + " " + sal2);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //6、释放资源;从小到大关闭
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

2. Use MyBatis code

mybatis is MyBatis SQL Mapper Framework for Java (sql mapping framework)

(1) sql mapper: sql mapping

Map a row of data in the database table into a java object

A row of data can be regarded as a Java object; operating this object is equivalent to operating the data in the table

(2) Data Access Objects (DAOs): data access, perform additions, deletions, modifications and queries on the database

MyBatis framework

[1] Provides the ability to create, destroy, and close Connection, Statement, ResultSet and other objects

【2】Provides the ability to execute sql statements

[3] Provides the ability to loop SQL and convert SQL results into Java objects and List collections.

2. Getting Started with MyBatis SqlSession

First use the mybatis framework in the form of SqlSession

First, let’s set up maven’s local warehouse

 1. Create a new database table user

CREATE TABLE `user` (
  `user_id` int(10) NOT NULL COMMENT '用户名ID',
  `user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
  `email` varchar(80) DEFAULT NULL COMMENT '用户邮箱',
  `age` int(5) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.Configure pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>maven-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <!--    <modules>-->
    <!--        <module>untitled</module>-->
    <!--    </modules>-->

    <properties>
        <!-- 源码编译 jdk 版本 -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <!-- 运行代码的 jdk 版本 -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <!-- 项目构建使用的编码,避免中文乱码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!--项目引入插件所需要的额外依赖 -->
    <dependencies>
        <!--参见dependencies/dependency元素 -->
        <!-- 单元测试依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.junit.jupiter</groupId>-->
<!--            <artifactId>junit-jupiter</artifactId>-->
<!--            <version>RELEASE</version>-->
<!--            <scope>compile</scope>-->
<!--        </dependency>-->
<!--        json转换依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory><!--所在的目录-->
                <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <!-- filtering 选项 false 不启用过滤器, *.property 已经起到过滤的作用了 -->
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. Create java entity class User

package com.example.domain;
 
public class User {
    private int userId;//  对应数据表User user_id
    private String userName;//  对应数据表User user_name
    private String email;  // 对应数据表User email
    private int age;// 对应数据表User age
 
    public int getUserId() {
        return userId;
    }
 
    public void setUserId(int userId) {
        this.userId = userId;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

4. Create the dao interface of the persistence layer

UserDao.java

Used to define methods for operating the database

package org.example.dao;

import org.example.domain.User;

import java.util.List;

/**
 * 用户的持久层接口
 * 继承该接口的类,实现接口中的方法,就可以实现对user表的增删改查
 */
public interface UserDao {
    /**
     * 查询user列表
     * @param user 单个user用户     [入参是user对象]
     * @return user的list
     */
    List<User> selectUserList(User user);  // 方法名和mapper.xml中的id值一致

    /**
     * 插入user
     * @param user
     * @return
     */
    int insertUser(User user);// 方法名和mapper.xml中的id值一致
}

The UserDao interface defines two methods, and classes that inherit this interface must implement these two interface methods.

For the methods in the above two interfaces, the input parameter is an entity class User object, that is, the previous step 3 defines a row of table data corresponding to a java object, and operating the object is to operate the row of data in the data table.

5. Mapping file

Create a configuration file SQL mapping file used by mybatis

To write SQL statements, generally a table corresponds to a SQL mapping file, which is an xml file.

sql mapping file (sql mapper)

Write SQL statements, and mybatis is responsible for executing these SQL statements.

UserDao.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">

<!--
    sql映射文件(sql mapper):编写SQL语句,mybatis负责执行这些SQL语句
    1、指定约束文件
    <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     mybatis-3-mapper.dtd:约束文件名称
    2、约束文件作用:限制,检查当前文件中出现的标签,属性必须符合mybatis的要求
    3、<mapper>:当前文件根标签(必须的)
       namespace:命名空间(唯一值,自定义字符串;要求使用dao接口的全限定名称)
       全限定类名:就是类名全称,带包路径的用点隔开,如: java.lang.String
          即全限定名 = 包名 + 类型
       非限定类名也叫短名,就是我们平时说的类名,不带包的,如:String
    4、数据库增删改查特定标签
       <select>:查询,select语句
       <update>:更新,update语句
       <insert>:插入,insert语句
       <delete>:删除,delete语句
-->

<mapper namespace="com.example.dao.UserDao">

    <!--
        <select>标签:查询操作
        id:执行SQL语法的唯一标识,mybatis会根据这个id的值来找到要执行的SQL语句
            可以自定义,一般要求使用接口中的方法名称
        resultType:表示结果类型,SQL语句执行后得到ResultSet结果集,遍历这个结果集得到的Java对象类型
            值写Java对象的全限定名称
    -->
    <select id="selectUserList" resultType="com.example.domain.User">
        select user_Id,user_Name,email,age
        from user
        order by user_Id asc
    </select>

    <!--插入操作,字段名和Java实体类中字段保持一致-->
    <insert id="insertUser">
        insert into user values(#{userId},#{userName},#{email},#{age})
    </insert>

</mapper>

6. Create the main configuration file of mybatis

The main configuration file provides database connection information  and SQL mapping file location information. There is one main configuration file for each project.

 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">

        <!--
            mybatis的主配置文件:主要定义了数据库的配置信息,SQL映射文件的位置
            1、约束文件
                <!DOCTYPE configuration
                    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                    "http://mybatis.org/dtd/mybatis-3-config.dtd">
                mybatis-3-config.dtd:约束文件名称
            2、configuration:根标签
        -->
<configuration>

<!-- settings:mybatis全局行为 -->
<settings>
    <!-- 设置mybatis输出日志 -->
    <setting name="logImpl" value="STDOUT_LOGGING" />
</settings>

<!--
    环境配置:数据库的连接信息
        default:必须和某个environment的id值一样
        告诉mybatis使用哪个数据库的连接信息(访问哪个数据库)
-->
<environments default="development">

    <!--
        environment:一个数据库的配置,环境
        id:一个唯一值(可自定义,表示环境的名称)
     -->
    <environment id="development">
        <!--
            transactionManaer:mybatis的事务类型
                type:JDBC(表示使用JDBC中的Connection对象的commit,rollback做事务处理)
        -->
        <transactionManager type="JDBC"/>
        <!--
            dataSource:表示数据源,连接数据库的
                type:表述数据源的类型,POOLED表示使用连接池
        -->
        <dataSource type="POOLED">
            <!--
               driver, user, username, password 是固定的,不能自定义。
            -->
            <!-- 数据库驱动类名 -->
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <!-- 连接数据库的URL字符串 -->
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
            <!-- 访问数据库的用户名 -->
            <property name="username" value="root"/>
            <!-- 访问数据库的密码 -->
            <property name="password" value="lyc123456"/>
        </dataSource>
    </environment>

    <!--表示线上的数据库,是项目真实使用的库-->
    <environment id="online">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
            <property name="username" value="root"/>
            <property name="password" value="lyc123456"/>
        </dataSource>
    </environment>

</environments>

<!-- sql mapper(SQL映射文件)的位置 -->
<mappers>
    <!--
        一个mapper标签指定一个文件的位置
            从类路径开始的路径信息(target/classes)类路径
    -->
    <mapper resource="org/mybatis/example/UserDao.xml"/>
</mappers>
</configuration>

Each table will be configured with a mapper, which is an xml file.

7. Create a test class using mybatis

Access the database through mybatis

package org.example;

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.example.domain.User;
import org.example.utils.MyBatisUtil;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {
    /**
     * 查询user列表
     */
    @Test
    public void testSelectUserList(){
        try {
            //访问mybatis读取user数据
            //1、定义mybatis主配置文件名称,从类路径的根开始(target/clasess)
            String config = "mybatis-config.xml";
            //2、读取config表示的文件
            InputStream in = Resources.getResourceAsStream(config);
            //3、创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //4、创建SqlSessionFactory对象
            SqlSessionFactory factory = builder.build(in);
            //5、获取SqlSession对象,从SqlSessionFactory中获取SqlSession(非自动提交事务,如果增删改需要手动提交事务)
            SqlSession sqlSession = factory.openSession();
            //6、指定要执行的SQL语句标识;sql映射文件中的 namespace + "." + 标签的id值
            String sqlId = "org.example.dao.UserDao.selectUserList";
            //7、执行sql语句,通过sqlId找到语句
            List<User> userList = sqlSession.selectList(sqlId);
            //8、输出结果
            for (User user:userList){
                System.out.println("查询用户="+user);
            }
            //9、关闭SQLSession对象
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询user列表
     */
    @Test
    public void testMyBatisUtil(){
        try {
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            String sqlId = "com.example.dao.UserDao.selectUserList";
            //7、执行sql语句,通过sqlId找到语句
            List<User> userList = sqlSession.selectList(sqlId);
            //8、输出结果
            for (User user:userList){
                System.out.println("查询用户="+user);
            }
            //9、关闭SQLSession对象
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入
     */
    @Test
    public void testInsertUser(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            String sqlId = "com.mycompany.dao.UserDao.insertUser";
            //7、执行sql语句,通过sqlId找到语句
            User user = new User();
            user.setUserId(5);
            user.setUserName("zhangfei");
            user.setEmail("[email protected]");
            user.setAge(16);
            int nums = sqlSession.insert(sqlId,user);

            //mybatis默认不是自动提交事务的, 所以在insert ,update ,delete后要手工提交事务
            sqlSession.commit();

            System.out.println("更新用户条数="+nums);

            //9、关闭SQLSession对象
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7. Extract SqlSession into tool class MyBatisUtil

MyBatisUtil.java
package org.example.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;

public class MyBatisUtil {
    public MyBatisUtil() {
    }

    public static SqlSession getSqlSession() throws IOException {
        String config = "mybatis-config.xml";
        InputStream ins = Resources.getResourceAsStream(config);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(ins);
        SqlSession sqlSession = factory.openSession();
        return sqlSession;
    }
}

Subsequent use of sqlSession instantiates this tool class MyBatisUtils class

(1)Resources

A class in mybatis, responsible for reading the main configuration file

//    1、定义mybatis主配置文件名称,从类路径的根开始(target/clasess)
String config = "mybatis-config.xml";
 
//    2、读取config表示的文件
InputStream in = Resources.getResourceAsStream(config);

(2)SqlSessionFactoryBuilder

Create SqlSessionFactory object 

//    3、创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
 
//    4、创建SqlSessionFactory对象
SqlSessionFactory factory = builder.build(in);

Complete catalog

10. Common error reporting issues

(1) The mybatis-config.xml file or the corresponding dao and SQL mapping files cannot be found

Three solutions:

【1】Maven clean, then compile, the target directory will be regenerated

【2】Rebuild Project, and then run it again, the mybatis-config.xml file will appear in the target directory.

[3] If the above two methods do not work, directly copy the src/resources/mybatis-config.xml file to the target/classes directory manually.

 (2) The methods of the dao interface must be consistent with the id in the dao.xml mapping file (key point)

 (3) The column names in the database table must be consistent with the fields in the Java entity class and the attribute fields in the dao.xml mapping file (key points)

11. junit: unit testing

junit: unit testing, a tool library used for testing methods. Unit: specifies a method. There are many methods in a class, and one method is called a unit.

Use unit tests

(1) Need to add junit dependency

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
</dependency>

(2) Create test class

Create a class in the src/test/java directory

(3) Create test methods

【1】public method

【2】No return value void 

【3】Customize the method name. The recommended name is test + test method name.

【4】The method has no parameters

【5】Add @Test above the method, the method can be executed separately; there is no need to use the main method

Supongo que te gusta

Origin blog.csdn.net/u013302168/article/details/132839097
Recomendado
Clasificación