mybatis 入门搭建

首先导包

依赖如下

<dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

构建SqlSessionFactory

MyBatis应用是以SqlSessionFactory为中心的,实例可以通过SqlSessionFactoryBuilder获得.
其中SqlSessionFactory是工厂接口,任务用于创建SqlSession
配置文件将会解析配置XML文件在Configuration类对象中.

配置XML获取数据源,事务管理器,映射器

在resource文件下新建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>
    <!-- 定义别名 -->
    <typeAliases>
        <typeAlias type="com.ming.Role" alias="role"/>
    </typeAliases>
    
    <!-- 定义数据库信息 -->
    <environments default="development">
        <environment id="development">
            <!-- jdbc事物管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据库链接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/>
                <property name="username" value="mybatis"/>
                <property name="password" value="ABCcba20170607"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

新建类

package com.ming;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class Role {
    public String getSqlSessionFactory(){
        String resource = "mybatis-config.xml";
        try {// 获得输入流
            InputStream inputStream;
            inputStream = Resources.getResourceAsStream(resource);
            // 获得SqlSessionFactory工厂
            SqlSessionFactory sqlSessionFactory = null;
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}

最后新建测试类

package com.ming;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class RoleTest {
    private Role role = null;
    @Before
    public void setUp() throws Exception {
        this.role = new Role();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getSqlSessionFactory() {
        role.getSqlSessionFactory();
    }
}

此时的目录结构
mybatis 入门搭建

代码方式构建

public SqlSessionFactory getSqlSessionFactory1(){
        // 创建数据库连接池
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis");
        dataSource.setUsername("mybatis");
        dataSource.setPassword("ABCcba20170607");
        // 构建数据库事物
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        // 创建数据库环境
        Environment environment = new Environment("development", transactionFactory, dataSource);
        // 构建Configuration对象
        Configuration configuration = new Configuration(environment);
        // 注册上下文别名
        configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
        // 创建映射器
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory;
    }

书写测试用例如下

package com.ming;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class RoleTest {
    private Role role = null;
    @Before
    public void setUp() throws Exception {
        this.role = new Role();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getSqlSessionFactory() {
        role.getSqlSessionFactory();
    }

    @Test
    public void getSqlSessionFactory1() {
        role.getSqlSessionFactory1();
    }
}

创建SqlSession

SqlSession属于门面,通过SqlSession可以获得需要的什么信息

SqlSession sqlSession = null;
        try{
            // 创建一个sqlsession会话
            sqlSession = sqlSessionFactory.openSession();
            sqlSession.commit();
        }catch (Exception e){
            // 输出错误信息
            System.out.println(e.getMessage());
            // 进行事物操作,回滚数据库数据
            sqlSession.rollback();
        }finally {
            // 进行资源关闭
            if(sqlSession != null){
                sqlSession.close();
            }
        }

SqlSession作用,获取映射器,通过命名信息执行sql结果

映射器

映射器由java和xml文件共同组成,作用
定义参数类型
描述缓存
描述sql
定义查询结果和POJO映射关系

先给出java接口

package com.ming;

public interface RoleMapper {
    public Role getRole(Long id);
}

根据给定的id获取角色对象

给出映射文件,然后在生成的时候会根据接口实现类,生成对象.

先编写POJO

package com.ming;

// POJO
public class Role {
    private int id;
    private String roleName;
    private String note;

    public void setId(int id) {
        this.id = id;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public int getId() {
        return id;
    }

    public String getRoleName() {
        return roleName;
    }

    public String getNote() {
        return note;
    }
}

在编写映射配置文件

<?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">
<!-- 定义接口类 -->
<mapper namespace="com.ming.RoleMapper">
    <!-- 定义的接口方法为getRole 类型参数为long 返回的结果为role 即之前定义在xml文件中定义的vo别名 -->
    <select id="getRole" parameterType="int" resultType="role">
        <!-- 定义sql语句-->
        SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}
    </select>
</mapper>

最后编写mybatis,添加映射器配置文件

<?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>
    <!-- 定义别名 -->
    <typeAliases>
        <typeAlias type="com.ming.Role" alias="role"/>
    </typeAliases>
    
    <!-- 定义数据库信息 -->
    <environments default="development">
        <environment id="development">
            <!-- jdbc事物管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据库链接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/>
                <property name="username" value="mybatis"/>
                <property name="password" value="ABCcba20170607"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 定义映射器 -->
    <mappers>
        <mapper resource="RoleMapper.xml"></mapper>
    </mappers>
</configuration>

最后再编写执行sql的类

package com.ming;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;

public class MyBatis {
    public String getSqlSessionFactory(){
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory = null;
        try {// 获得输入流
            InputStream inputStream;
            inputStream = Resources.getResourceAsStream(resource);
            // 获得SqlSessionFactory工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
        SqlSession sqlSession = null;
        try{
            // 创建一个sqlsession会话
            sqlSession = sqlSessionFactory.openSession();
            // 获得映射器
            // 接口传入映射器中
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            // 执行方法
            Role role = roleMapper.getRole(0);
            System.out.println(role.getRoleName());
            // 刷新语句并提交链接
            sqlSession.commit();
        }catch (Exception e){
            // 输出错误信息
            System.out.println(e.getMessage());
            // 进行事物操作,回滚数据库数据
            sqlSession.rollback();
        }finally {
            // 进行资源关闭
            if(sqlSession != null){
                sqlSession.close();
            }
        }
        return null;
    }

    public SqlSessionFactory getSqlSessionFactory1(){
        // 创建数据库连接池
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis");
        dataSource.setUsername("mybatis");
        dataSource.setPassword("ABCcba20170607");
        // 构建数据库事物
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        // 创建数据库环境
        Environment environment = new Environment("development", transactionFactory, dataSource);
        // 构建Configuration对象
        Configuration configuration = new Configuration(environment);
        // 注册上下文别名
        configuration.getTypeAliasRegistry().registerAlias("role", MyBatis.class);
        // 创建映射器
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory;
    }
}

最后编写测试类

package com.ming;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MyBatisTest {
    private MyBatis myBatis = null;
    @Before
    public void setUp() throws Exception {
        this.myBatis = new MyBatis();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getSqlSessionFactory() {
        myBatis.getSqlSessionFactory();
    }

    @Test
    public void getSqlSessionFactory1() {
        myBatis.getSqlSessionFactory1();
    }
}

执行单元测试
结果如下
mybatis 入门搭建

即完成了MyBatis的一次查询

注解

定义接口

package com.ming;

import org.apache.ibatis.annotations.Select;

public interface Role1 {
    @Select (value="SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}")
    public Role getRole(int id);
}

生命周期

SqlSessionFactoryBuilder

其是利用xml或者java编码构建SqlSessionFactory 可以构建多个SessionFactory 作用 构建器
根据构建器获得sqlSessionFactory

SqlSessionFactory

创建SqlSession 一个SqlSession相当于JDBC的Connection对象
此为单例管理
每创建一个SqlSession就会创建一个数据库连接

SqlSession

此为一个会话,相当于一个Connection连接 线程不安全
生命周期为一个应用的请求和操作,可以执行多条sql

相关推荐