关注小程序 找一找教程网-随时随地学编程

XML教程

Mybatis 快速入门(XML方式)第一天

导读

架构原理图

 

说明

mybatis配置文件

  1. SqlMapConfig.xml,此文件为mybatis的全局配置文件,配置了mybatis的运行环境等信息
  2. XXXMapper.xml,此文件作为mybatis的sql映射文件,文件中配置了操作数据库的CRUD语句。需要在SqlMapConfig.xml中加载

SqlSessionFactory

  1. 通过mybatis环境等配置信息构造SqlSessionFactory,既会话工厂

***跟底层源码查看创建SqlSessionFactory流程***

注:底层如何获取标签值,请自行研究(剧透:for循环遍历XML获取标签中的值,然后放入Map)!~

SqlSession

  1. 通过会员工厂创建SqlSession即会话,程序通过SqlSession会话接口对数据库进行CRUD操作。

Executor执行器

  mybatis底层自定义了Executor执行器接口来具体操作数据库,Executor接口有两个实现,一个是基本执行器(默认),一个缓存执行器,SqlSession底层是通过executor接口操作数据库

Mapped Statement

  他是mybatis一个底层封装对象,包装了mybatis配置信息及XXXMapper.xml映射文件等。XXXMapper.xml文件中一个个select/insert/update/delete标签对应一个Mapped Statement对象

原始JDBC代码

  原始JDBC和mybatis操作数据库数据,与上面架构图流程相对应。

 public class JDBCTest {
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> main(String[] args) {
    Connection connection </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
    PreparedStatement preparedStatement </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
    ResultSet resultSet </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;

    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 加载数据库驱动</span>
        Class.forName("com.mysql.jdbc.Driver"<span style="color: #000000;">);

        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 通过驱动管理类获取数据库链接connection = DriverManager</span>
        connection =<span style="color: #000000;"> DriverManager.getConnection(
                          </span>"jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"<span style="color: #000000;">,
                         </span>"root"<span style="color: #000000;">, 
                          </span>"root"<span style="color: #000000;">
                          );

        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 定义sql语句 ?表示占位符</span>
        String sql = "select * from user where username = ?"<span style="color: #000000;">;
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 获取预处理 statement</span>
        preparedStatement =<span style="color: #000000;"> connection.prepareStatement(sql);
        
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的</span>
        preparedStatement.setString(1, "王五"<span style="color: #000000;">);
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 向数据库发出 sql 执行查询,查询出结果集</span>
        resultSet =<span style="color: #000000;"> preparedStatement.executeQuery();
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 遍历查询结果集</span>
        <span style="color: #0000ff;">while</span><span style="color: #000000;"> (resultSet.next()) {
            System.out.println(
                              resultSet.getString(</span>"id"<span style="color: #000000;">) 
                              </span>+ " " +<span style="color: #000000;"> 
                              resultSet.getString(</span>"username"<span style="color: #000000;">)
                 );
        }
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception e) {
        e.printStackTrace();
    } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> {
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 释放资源</span>
        <span style="color: #0000ff;">if</span> (resultSet != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
            </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
                resultSet.close();
            } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (SQLException e) {
                e.printStackTrace();
            }
        }
        </span><span style="color: #0000ff;">if</span> (preparedStatement != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
            </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
                preparedStatement.close();
            } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (SQLException e) {
                e.printStackTrace();
            }
        }
        </span><span style="color: #0000ff;">if</span> (connection != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
            </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
                connection.close();
            } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (SQLException e) {
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated catch block e.printStackTrace();</span>

                }
}
}
}
} 

Mybatis 入门基础

表结构

 表数据

Mybatis环境搭建 

添加依赖

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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cyb</groupId>
    <artifactId>mybatis</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- mysql依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
    <span style="color: #008000;">&lt;!--</span><span style="color: #008000;"> 单元测试 </span><span style="color: #008000;">--&gt;</span>
    <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">dependency</span><span style="color: #0000ff;">&gt;</span>
        <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">groupId</span><span style="color: #0000ff;">&gt;</span>junit<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">groupId</span><span style="color: #0000ff;">&gt;</span>
        <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">artifactId</span><span style="color: #0000ff;">&gt;</span>junit<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">artifactId</span><span style="color: #0000ff;">&gt;</span>
        <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">version</span><span style="color: #0000ff;">&gt;</span>4.12<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">version</span><span style="color: #0000ff;">&gt;</span>
    <span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">dependency</span><span style="color: #0000ff;">&gt;</span>
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">dependencies</span><span style="color: #0000ff;">&gt;</span>
<span style="color: #0000ff;">&lt;</span><span style="color: #800000;">build</span><span style="color: #0000ff;">&gt;</span>
    <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">finalName</span><span style="color: #0000ff;">&gt;</span>mybatis<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">finalName</span><span style="color: #0000ff;">&gt;</span>
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">build</span><span style="color: #0000ff;">&gt;</span>

</project> 

SqlMapConfig.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>
    <!-- 引入外部配置文件 -->
    <properties resource="db.properties"></properties>
    <!-- 数据库链接相关 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 添加映射文件 -->
        <mapper resource="UserMapper.xml" />
    </mappers>
</configuration> 

db.properties

 db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/cyb
db.username=root
db.password=root 

UserMapper.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:为了分类管理映射文件中的MappedStatement -->
<mapper namespace="test">
<select id="queryUserById" parameterType="int" resultType="com.cyb.mybatis.demo.User">
        select * from user where id = #{id} 
    </select>
</mapper> 

User.java

 package com.cyb.mybatis.demo;
import java.util.Date;
public class User {
private int id;
private String username;
private Date birthday;
private int sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
+ address + "]";
}
} 

MybatisDemo.java

 package com.cyb.mybatis.demo;
import java.io.InputStream;
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.Before;
import org.junit.Test;
public class MybatisDemo {
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> SqlSessionFactory sqlSessionFactory;

@Before
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> init() <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Exception {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">指定全局配置文件路径</span>
    String resource = "SqlMapConfig.xml"<span style="color: #000000;">;
    </span><span style="color: #008000;">//</span><span style="color: #008000;">加载资源文件(包括全局文件和映射文件)</span>
    InputStream inputStream =<span style="color: #000000;"> Resources.getResourceAsStream(resource);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">使用构建者模式创建SqlSessionFactory</span>
    sqlSessionFactory = <span style="color: #0000ff;">new</span><span style="color: #000000;"> SqlSessionFactoryBuilder().build(inputStream);
}

@Test
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> testSelect() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">由SqlSessionFactory工厂去创建SqlSession(会话)</span>
    SqlSession sqlSession =<span style="color: #000000;"> sqlSessionFactory.openSession();
    </span><span style="color: #008000;">//</span><span style="color: #008000;">调用SqlSession接口,去实现数据库的CRUD</span>
    User user = sqlSession.selectOne("test.queryUserById", 1<span style="color: #000000;">);
    System.out.println(user);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">释放资源</span>

        sqlSession.close();
}
} 

项目结构

测试

功能实现

根据用户id查询一个用户信息

根据用户名称模糊查询用户信息列表

添加用户

更新用户

删除用户