MyBatis use in Maven (Java SE) project

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr__Viking/article/details/91429150

Preface

Today's developers have basically been highly integrated, and a lot of technology that we just need some simple configuration can immediately out of the box. But when we need to quickly write some small tools, to configure a SSM or some other integration framework of the project portfolio, often more troublesome, and we do not necessarily need to fully integrate all of these things. For example, we need to write a gadget similar to reptiles like grab some pages, then we can choose only pure java SE reconfiguration project for a bridge Mybatis database on the line, use is also very light and easy. Now we have to analyze how a pure java SE project to MyBatis set of things with them.

table of Contents

1. Import jar packets associated MyBatis

2. Configure MyBatis.xml

3. Read the profile creation SqlSessionFactory

4. The method of encapsulation used


1. Import jar packets associated MyBatis

Maven depends directly, as follows:

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>

2. Configure MyBatis.xml

For us in the project are concentrated mainly MyBatis configuration with this file, so this file is relatively complicated, and depends on the details of the comments in the code.

<?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="config/mysql.properties" />
    <!-- 全局变量配置 -->
    <settings>
        <!-- 开启驼峰命名法转换 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 不使用权限定名称时配置简称(两种方式,1.直接配置包名称;2.为每一个DO配置简称) -->
    <typeAliases>
        <package name="com.**.model"/>
        <!--<typeAlias alias="Book" type="com.spider.model.Book" />-->
    </typeAliases>
    <!-- 配置数据源环境(可多个,但必须配置default数据源) -->
    <environments default="development">
        <!-- 第一个数据源 -->
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}" />
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.user}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
        <!-- 第二个数据源 -->
        <environment id="dataSource2">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${DS-2.driver}" />
                <property name="url" value="${DS-2.url}"/>
                <property name="username" value="${DS-2.user}"/>
                <property name="password" value="${DS-2.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 将mapper.xml映射到mybatis中(这里的xml文件如果是放在resource目录下面的话就必须老老实实配置每一个xml文件,如果是放在src下面某一个包内,可以用package指定包路径) -->
    <mappers>
        <mapper resource="dao/BookMapper.xml"/>    
        <!--<package name="com.spider.dao"/>-->
    </mappers>
</configuration>

3. Read the profile creation SqlSessionFactory

The configuration file path in the code into their path.

    // mybatis相关参数
    private final static String CONFIG_PATH = "config/mybatis.xml";
    private static InputStream input;
    private SqlSession sqlSession;

    private void init(String environment){
        try {
            input = Resources.getResourceAsStream(CONFIG_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 通过mybatis配置文件和environment名称获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input, environment);
        // 开启自动提交,否则的话需要自己在执行完操作后手动提交
        sqlSession = sqlSessionFactory.openSession(true);
    }

4. The method of encapsulation used

We just need to use nothing less than SqlSession when using MyBatis to create Mapper instance object, so we use a generic method to create an instance of the specified type of Mapper.

public <T> T getMapper(Class<T> clazz){
        return sqlSession.getMapper(clazz);
    }

Finally, I then my java code stickers:

package com.spider.util;

import org.apache.commons.lang.StringUtils;
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;

/**
 * Created by Viking on 2019/6/11
 * 封装MyBatis的初始化及构造mapper的一些方法
 */
public class MyBatisUtil {
    // mybatis相关参数
    private final static String CONFIG_PATH = "config/mybatis.xml";
    private static InputStream input;
    private SqlSession sqlSession;

    private void init(String environment){
        try {
            input = Resources.getResourceAsStream(CONFIG_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 通过mybatis配置文件和datasource名称获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input, environment);
        // 设置自动提交
        sqlSession = sqlSessionFactory.openSession(true);
    }
    // 使用默认datasource环境的构造器
    public MyBatisUtil(){
        init(null);
    }
    // 使用指定datasource环境的构造器
    public MyBatisUtil(String environment){
        init(environment);
    }
    // 创建Mapper实例
    public <T> T getMapper(Class<T> clazz){
        return sqlSession.getMapper(clazz);
    }
    // 关闭连接,使用结束后必须执行
    public void close(){
        if (null != sqlSession) {
            sqlSession.close();
        }
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

Guess you like

Origin blog.csdn.net/Mr__Viking/article/details/91429150