MyBatis项目快速搭建及MySQL一个Statement支持多条命令参数
一、简述
本文以笔记的形式,记录一个基本Mybatis项目的使用,方便后期项目使用到相关配置时直接复制使用。
二、项目结构

pom.xml中的依赖
<!-- 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>
三、文件信息
1、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>
<!--配置环境 -->
<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&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai&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中时,原来的"&"需要使用"&"来转义。(2)、如果想最终执行时一个Mapper文件的每一个update/insert/select等Statement中支持多个sql语句的话,需要在连接URL中加入‘allowMultiQueries=true’,切记!
2、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();
}
3、SqlSessionFactoryUtil工具类
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);
} }
4、InitMapperService服务类
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();
}
}
5、MapperTest.java
@Test
public void testInitData()
{
InitMapperService initMapperService=new InitMapperService();
initMapperService.initData();
}
MyBatis项目快速搭建及MySQL一个Statement支持多条命令参数的更多相关文章
- 新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial
新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial 作者:韩梦飞沙 Auth ...
- 如何基于 Docker 快速搭建 Springboot + Mysql + Redis 项目
目录 前言 项目目录 搭建项目 1. docker安装启动mysql以及redis 1.1 安装mysql 1.2 安装redis 2. 初始化数据库 3.创建项目 4.初始化代码 4.1 全局配置文 ...
- USBWebServer 中文便携版 快速搭建 PHP/MySQL 网站服务器环境
如果你是一位 WEB 开发者,或正在学习网页编程,你一定会发现,每到一台新电脑上想要在本地调试测试/运行网站代码都得搭建配置一遍 WAMP (Win.Apache.PHP.MySQL) 环境简直烦透了 ...
- springboot项目快速搭建
1. 问题描述 springboot的面世,成为Java开发者的一大福音,大大提升了开发的效率,其实springboot只是在maven的基础上,对已有的maven gav进行了封装而已,今天用最简单 ...
- ssm项目快速搭建(注解)-依赖
父层jar包版本控制,管理配置 <!-- 集中定义依赖版本号 --> <properties> <junit.version>4.12</ ...
- 批量给文件加一个后缀 .bak , 一条命令去掉文件的后缀 linux
给当前文件夹下面的所有文件加上一个后缀 == 一条命令解决 ll | awk '{print $9}' | grep -v '^[ ]*$' |sed -r 's#(.*)#mv \1 \1.bak# ...
- maven项目快速搭建SSM框架(一)创建maven项目,SSM框架整合,Spring+Springmvc+Mybatis
首先了解服务器开发的三层架构,分配相应的任务,这样就能明确目标,根据相应的需求去编写相应的操作. 服务器开发,大致分为三层,分别是: 表现层 业务层 持久层 我们用到的框架分别是Spring+Spri ...
- springboot + shiro + mysql + mybatis 工程快速搭建
1. 新建 springboot 工程 2. 随便起个名字 3. 初始化工程 4. 导入 shiro 和 thymeleaf 依赖 <!-- thymeleaf依赖 --> <dep ...
- 【分享】标准springMVC+mybatis项目maven搭建最精简教程
文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...
随机推荐
- Validation failed for object='employee'. Error count: 1问题解决
2018-11-13 在表单提交时有时候会提示 Validation failed for object=’user’. Error count: 1,其中user是表的名字,Error count是 ...
- detailFormatter bootstrapTable
detailView : true,//会导致表格最开头多出一列 detailFormatter :function(index, row, element){ var image = '<di ...
- ClassLoader家族
DexClassLoader可以加载外部的dex,而PathClassLoader只能加载内部的dex 双亲委托 ClassLoader(ClassLoader parentLoader,boolea ...
- python实现杨辉三角
刚刚学python,原来用c++,Java很轻松实现的杨辉三角,现在用python实现,代码是少了,理解起来却不容易啊. 这里主要用到的Python的生成器. 我们都知道Python有列表解析功能,根 ...
- QLayout: Attempting to add QLayout XXX to XXX, which already has a layout
QLayout是Qt应用开发中一个非常重要的组件,然而平时使用的时候不小心经常会发现控制台有类似如下的警告: QLayout: Attempting to add QLayout "&quo ...
- c++ <vector>学习
https://www.cnblogs.com/mr-wid/archive/2013/01/22/2871105.html 具体参考上面博客,很详细,也是看他的.今天c++学习200%,项目开发0% ...
- 解决Python自带的json不能序列化data,datetime类型数据问题
官方文档中的一个Demo: >>> import json >>> class ComplexEncoder(json.JSONEncoder): ... def ...
- C# 使用PrintDocument 绘制表格 完成 打印预览
C# 使用PrintDocument 绘制表格 完成 打印预览 DataTable 经过不断的Google与baidu,最终整理出来的打印类 主要是根据两个参考的类组合而成,稍微修改了一下,参考代 ...
- SQL总结——存储过程
SQL总结(五)存储过程 概念 存储过程(Stored Procedure):已预编译为一个可执行过程的一个或多个SQL语句. 创建存储过程语法 CREATE proc | procedure pro ...
- 权限框架Apache Shiro 和 Spring Security
Shiro 首先Shiro较之 Spring Security,Shiro在保持强大功能的同时,还在简单性和灵活性方面拥有巨大优势.Shiro是一个强大而灵活的开源安全框架,能够非常清晰的处理认证.授 ...