MyBatis項目快速搭建及MySQL一個Statement支持多條命令參數

1、簡述java

  本文以筆記的形式,記錄一個基本Mybatis項目的使用,方便後期項目使用到相關配置時直接複製使用。mysql

 

2、項目結構sql

  

  pom.xml中的依賴apache

  

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

 

3、文件信息session

  一、mybatis-config.xmlmybatis

<?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"/>
            <!--數據源 經過Properties加載配置 -->
            <dataSource type="POOLED">
                <!--驅動driver  -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!--鏈接URL  -->
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;allowMultiQueries=true"/>
                <!--用戶名  -->
                <property name="username" value="root"/>
                <!--密碼  -->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--創建映射  -->
    <mappers>
        <mapper resource="mappers/InitMapper.xml"/>
        <mapper resource="mappers/ConfigureMapper.xml"/>
    </mappers>
</configuration>

  注意,(1)、鏈接URL位於xml中時,原來的"&"須要使用"&amp;"來轉義。(2)、若是想最終執行時一個Mapper文件的每個update/insert/select等Statement中支持多個sql語句的話,須要在鏈接URL中加入‘allowMultiQueries=true’,切記!app

 

  二、InitMapper.xml和InitMapper.java工具

<?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.test.repository.mappers.InitMapper">
    <update id="ensureStationGroupTab">
        CREATE TABLE IF NOT EXISTS `station_group_tab`(
         `id` BIGINT NOT NULL AUTO_INCREMENT,
         `name` VARCHAR(255) COMMENT '組名稱',
         `notes` VARCHAR(255) COMMENT '備註',
         PRIMARY KEY (`Id`),
         INDEX `idx_station_group_groupName`(`groupName`)
         )ENGINE INNODB;
    </update>
    <update id="ensureConfigureTab">
      CREATE TABLE IF NOT EXISTS `configure_tab`(
        `id` BIGINT NOT NULL AUTO_INCREMENT,
        `stationGroupId` BIGINT COMMENT '站點組ID',
        `type` INT COMMENT '模塊',
        `name` VARCHAR(255) COMMENT '名稱',
        PRIMARY KEY (`Id`),
        INDEX `idx_configure_stationGroupId`(`stationGroupId`),
        CONSTRAINT `fk_configure_stationGroupId` FOREIGN KEY (`stationGroupId`) REFERENCES `station_group_tab`(`id`)
        )ENGINE INNODB;
    </update>
    <update id="ensureStationGroupRelationTab">
        CREATE TABLE IF NOT EXISTS `station_group_relation_tab`(
          `id` BIGINT NOT NULL AUTO_INCREMENT,
          `stationGroupId` BIGINT COMMENT '站點組ID' ,
          `otherInfo` VARCHAR(255) COMMENT '其它信息',
          PRIMARY KEY (`Id`),
          INDEX `idx_station_group_relation_stationGroupId`(`stationGroupId`),
          CONSTRAINT `fk_station_group_relation_stationGroupId` FOREIGN KEY (`stationGroupId`) REFERENCES `station_group_tab`(`id`)
        )ENGINE INNODB;
    </update>

    <update id="initDataTable">
      --  INSERT INTO  `station_group_tab` (name,notes) VALUES('ABC','ABC');
      --  INSERT INTO  `station_group_tab` (name,notes) VALUES('DEF','DEF');
    </update>
</mapper>
package com.test.repository.mappers;

public interface InitMapper {
    int ensureStationGroupTab();
    int ensureConfigureTab();
    int ensureStationGroupRelationTab();
    int initDataTable();
}

 

  三、SqlSessionFactoryUtil工具類ui

package com.test.repository.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.Reader;

public class SqlSessionFactoryUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 1.加載配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 2.建立SqlSessionFactory
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

}

 

  四、InitMapperService服務類url

package com.test.repository.services;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import com.test.repository.mappers.InitMapper;
import com.test.repository.utils.SqlSessionFactoryUtil;



public class InitMapperService {
    private final Logger log =     
    LoggerFactory.getLogger(InitMapperService.class);

    /** 建表語句 */
    public void createDataTable() {
        try {
            SqlSession session = SqlSessionFactoryUtil.getSqlSession(true);
            InitMapper mapper = session.getMapper(InitMapper.class);
            mapper.ensureStationGroupTab();
            mapper.ensureConfigureTab();
            mapper.ensureStationGroupRelationTab();
            session.close();
        } catch (Exception ex) {
            log.error("An error occurred while creating the data table.", ex);
        }
    }

    /** 初始化數據 */
    public void initDataTable() {
        try {
            SqlSession session = SqlSessionFactoryUtil.getSqlSession(true);
            InitMapper mapper = session.getMapper(InitMapper.class);
            mapper.initDataTable();
            session.close();
        } catch (Exception ex) {
            log.error("An error occurred while creating the data table.", ex);
        }
    }

    public void initData() {
        createDataTable();
        initDataTable();
    }
}
    

 

  五、MapperTest.java

    @Test
    public void testInitData()
    {
        InitMapperService initMapperService=new InitMapperService();
        initMapperService.initData();
    }
相關文章
相關標籤/搜索