spring5x-mybatis-base

![Spring5x-mybatis-druid-base参考目录.png](https://upload-images.jianshu.io/upload_images/15645795-48fc887bffa5ec62.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 目录补充:5、项目启动自动执行sql文件 **此目录作为参考,本次没有精确分出配置(分页插件配置)** Spring5x-mybatis-base此模块是从spring5x-base 基础模块扩展过来的 spring5x-base模块是一个非常干净的spring5.x+springMVC架构 如果没有搭建spring5x-base模块,请先参考: [spring5x-base模块搭建](https://www.jianshu.com/p/8612404cf1d6) **Spring5x-mybatis-base 是一个mybatis基础模块,今后的spring+mybatis 的xml配置方式,在此模块上扩展。** ## 搭建项目 **基于spring5x-base 基础模块 新增功能:** * 1、集成 druid/c3p0 + mysql/oracle * 2、集成 mybatis 配置 * 3、mapper 配置: - mybatis 增删改查操作 - 动态(trim) 插入数据 - mybatis+mysql 批量插入数据 - mybatis+oracle 批量插入数据 * 4、Mybatis-PageHelper 分页插件 * 5、项目启动自动执行sql文件 ### 1、集成 druid/c3p0 + mysql/oracle **** pom.xml 主要依赖 ```xml 5.0.9.RELEASE org.springframework spring-jdbc ${spring.version} mysql mysql-connector-java 8.0.13 com.oracle ojdbc6 11.2.0.3 com.alibaba druid 1.1.20 org.hibernate hibernate-c3p0 5.3.10.Final org.mybatis mybatis-spring 2.0.2 org.mybatis mybatis 3.5.2 com.github.pagehelper pagehelper 5.1.2 ``` **web.xml 配置druid** ```xml DruidStatView com.alibaba.druid.support.http.StatViewServlet resetEnable true loginUsername druid loginPassword druid DruidStatView /druid/* DruidWebStatFilter com.alibaba.druid.support.http.WebStatFilter exclusions *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* DruidWebStatFilter /* ``` **jdbc.properties** ```properties # 项目启动是否启动执行sql文件 true/false jdbc.isStartSql=true # mysql 数据库配置: mysql.jdbc.driverClassName=com.mysql.jdbc.Driver mysql.jdbc.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false mysql.jdbc.username=root mysql.jdbc.password=123456 mysql.jdbc.validationQuery=select 'x' # oracle 数据库配置: oracle.jdbc.driverClassName=oracle.jdbc.driver.OracleDriver oracle.jdbc.url=jdbc:oracle:thin:@127.0.0.1/orcl oracle.jdbc.username=duke oracle.jdbc.password=duke oracle.jdbc.validationQuery=select 'x' from dual ``` **spring-druid.xml ** > 注:MySQL和Oracle 数据库更换方式: > 只需要将spring-druid.xml 中 "配置mysql" 和 "配置oracle" 注释其中一个。 ```xml ``` spring-c3p0.xml ```xml ``` **spring-mvc.xml** ```xml ``` ### 2、集成 mybatis **** pom.xml 引入 mybatis和 分页插件配置 ```xml org.mybatis mybatis-spring 2.0.2 org.mybatis mybatis 3.5.2 com.github.pagehelper pagehelper 5.1.2 ``` mybatis-config.xml 配置 ```xml ``` spring-mvc.xml 配置 ```xml ``` UserEntity.java 实体类 ```java package com.zja.entity; import java.util.Date; /** * @author ZhengJa * @description User 对象 * @data 2019/10/29 */ public class UserEntity { private String name; private String age; private Date date; public UserEntity() { } public UserEntity(String name, String age,Date date) { this.name = name; this.age = age; this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "UserEntity{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", date=" + date + '}'; } } ``` > 建表语句:在项目中db文件夹下,含oracle和mysql UserDao.java 接口 ```java package com.zja.dao; import com.zja.entity.UserEntity; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author ZhengJa * @description UserDao 接口 * @data 2019/10/29 */ public interface UserDao { //静态插入数据:通用方法 int insertUser(UserEntity userEntity); //动态插入数据: mysql用法,id自增 int insertUserMysql(UserEntity userEntity); //动态插入数据:oracle用法,id使用序列 int insertUserOracle(UserEntity userEntity); //mybatis批量插入数据:mysql用法,id自增 int mysqlBatchSaveUser(@Param("userEntityList") List userEntities); //mybatis批量插入数据:oracle用法,id使用序列 int oracleBatchSaveUser(@Param("userEntityList") List userEntities); //按id查询用户 UserEntity queryUserById(Integer id); //查询所有用户 List queryAllUser(); //更新数据-改数据 int updateUser(UserEntity userEntity); //删除数据 int delUser(Integer id); } ``` ### 3、mapper 配置: **** resources/mappers文件夹下新建 UserEntity.xml,内容如下 ```xml id, username, age, createtime select from userentity t where t.id=#{id} select * from userentity insert into userentity(id, username, age, createtime) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{createTime,jdbcType=DATE}) insert into userentity id, username, age, createtime, #{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{createTime,jdbcType=DATE}, insert into userentity id, username, age, createtime, SEQ_MY_USER_HIBERNATE.NEXTVAL, #{userName,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{createTime,jdbcType=DATE}, insert into userentity(username, age, createtime) values (#{item.userName}, #{item.age}, #{item.createTime}) insert into userentity (id, username, age, createtime) select t.* from ( select #{item.id}, #{item.userName}, #{item.age}, #{item.createTime} from dual ) t update userentity username = #{userName}, age = #{age}, createtime = #{createTime}, where id=#{id} delete from userentity where id=#{id} ``` MybatisController.java ```java package com.zja.controller; import com.github.pagehelper.PageInfo; import com.zja.entity.UserEntity; import com.zja.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author ZhengJa * @description MybatisController 测试类 * @data 2019/10/29 */ @RestController @RequestMapping("rest/mybatis") @Api(tags = {"MybatisController"}, description = "mybatis简单测试") public class MybatisController { @Autowired private UserService userService; @PostMapping("insertUser") @ApiOperation(value = "静态插入数据:通用方法,必须传id值且id>0", notes = "插入数据(id不自增或不使用序列,必须传id值且id>0)", httpMethod = "POST") public int insertUser(@RequestBody UserEntity userEntity) { return this.userService.insertUser(userEntity); } @PostMapping("insertUserMysql") @ApiOperation(value = "动态插入数据: mysql用法 id自增,不传id值", notes = "插入数据(id自增,不传id值)", httpMethod = "POST") public int insertUserMysql(@RequestParam String userName,@RequestParam Integer age) { UserEntity userEntity = new UserEntity(); userEntity.setUserName(userName); userEntity.setAge(age); userEntity.setCreateTime(new Date()); return this.userService.insertUserMysql(userEntity); } @PostMapping("insertUserOracle") @ApiOperation(value = "动态插入数据:oracle用法 id使用序列,不传id值", notes = "插入数据(id使用序列,不传id值)", httpMethod = "POST") public int insertUserOracle(@RequestParam String userName,@RequestParam Integer age) { UserEntity userEntity = new UserEntity(); userEntity.setUserName(userName); userEntity.setAge(age); userEntity.setCreateTime(new Date()); return this.userService.insertUserOracle(userEntity); } @PostMapping("mysqlBatchSaveUser") @ApiOperation(value = "mybatis+mysql批量插入数据: mysql用法 id自增", notes = "插入数据(id自增)", httpMethod = "POST") public int mysqlBatchSaveUser(@ApiParam(value = "count 批量插入几条",defaultValue = "5") @RequestParam Integer count) { List entityList = new ArrayList<>(); for (int i=0;i entityList = new ArrayList<>(); for (int i=0;i queryAllUser() { return this.userService.queryAllUser(); } @GetMapping("getpage") @ApiOperation(value = "获取分页结果", notes = "分页查询", httpMethod = "GET") public List getPagingResults(@ApiParam("页码值") @RequestParam int pageNum, @ApiParam("每页显示条数") @RequestParam int pageSize) { return this.userService.getPagingResults(pageNum, pageSize); } @GetMapping("getpageinfo") @ApiOperation(value = "获取分页结果及分页信息", notes = "分页查询", httpMethod = "GET") public PageInfo queryPageInfo(@ApiParam("页码值") @RequestParam int pageNum, @ApiParam("每页显示条数") @RequestParam int pageSize) { return this.userService.queryPageInfo(pageNum, pageSize); } @PutMapping("updateUser") @ApiOperation(value = "更新用户信息", notes = "更新数据-改数据", httpMethod = "PUT") public int updateUser(@RequestBody UserEntity userEntity) { return this.userService.updateUser(userEntity); } @DeleteMapping("delUser") @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE") public int delUser(@RequestParam Integer id) { return this.userService.delUser(id); } } ``` ### 5、项目启动自动执行sql文件 resources/db/mysql/mysql-0-准备测试数据.sql ```sql -- 删表语句 drop table if exists userentity; -- 创建表 -- 用户表,如果表不存在,则创建,id自增且是主键,username不能null CREATE TABLE IF NOT EXISTS userentity( id bigint not null, username VARCHAR(50) not null, age int, createtime DATE, PRIMARY KEY (id) )ENGINE=InnoDB DEFAULT CHARSET=utf8; COMMIT; -- 插入数据语句 -- 增加USERENTITY表数据 insert into USERENTITY(id,username,age) values (1,'小明',18); insert into USERENTITY(id,username,age) values (2,'小刘',20); insert into USERENTITY(id,username,age) values (3,'小王',20); COMMIT; ``` resources/db/oracle/orcl-0-准备测试数据.sql ```sql -- 删除测试的表和数据 declare countCol number; countTab number; countSeq number; begin --===============20191203==================start -- 删除无用表 upper:小写字符转化成大写的函数 select count(*) into countTab from user_tables where table_name = upper('userentity'); if countTab = 1 then execute immediate 'drop table userentity'; end if; -- 删除无用序列 名称区分大小写 select count(*) into countSeq from user_sequences where sequence_name = 'SEQ_MY_USER'; if countSeq = 1 then execute immediate 'DROP SEQUENCE SEQ_MY_USER'; end if; --===============20191203==================end end;$$ -- oracle创建序列语句 -- SEQ_MY_USER-->userentity create sequence SEQ_MY_USER minvalue 1 maxvalue 9999999999999999999999999999 start with 1 increment by 1 cache 20 $$ -- oracle建表语句 -- 用户表 create table userentity ( id NUMBER(19) not null primary key, username VARCHAR2(255 char), createtime TIMESTAMP(6), age NUMBER(19) ) $$ COMMIT $$ --插入数据语句 -- userentity用户表数据准备 insert into USERENTITY(id,username,age) values (SEQ_MY_USER.NEXTVAL,'小明',21) $$ insert into USERENTITY(id,username,age) values (SEQ_MY_USER.NEXTVAL,'小刘',22) $$ insert into USERENTITY(id,username,age) values (SEQ_MY_USER.NEXTVAL,'小王',20) $$ COMMIT $$ ``` 代码执行sql文件 ```java /** * Date: 2019-12-03 14:19 * Author: zhengja * Email: [email protected] * Desc:ApplicationContext 应用上下文对象 */ @Component public class SpringContextGetter implements ApplicationContextAware { private ApplicationContext applicationContext; public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } /** * Date: 2019-12-03 14:17 * Author: zhengja * Email: [email protected] * Desc:Schema处理器 */ @Component public class SchemaHandler { //private final String SCHEMA_SQL = "classpath:schema.sql"; @Autowired private DataSource datasource; @Autowired private SpringContextGetter springContextGetter; /** * 执行判断数据源连接池 */ public void execute() throws Exception { //druid 判断数据库是mysql/oracle /*DruidDataSource druidDataSource = (DruidDataSource) this.datasource; Driver driver = druidDataSource.getDriver(); if (driver instanceof com.mysql.jdbc.Driver) { executeSqlFile("mysql"); } if (driver instanceof com.mysql.cj.jdbc.Driver) { executeSqlFile("mysql"); } if (driver instanceof oracle.jdbc.OracleDriver){ executeSqlFile("oracle"); } if (driver instanceof oracle.jdbc.driver.OracleDriver){ executeSqlFile("oracle"); }*/ //判断是c3p0/druid 连接池 if (datasource instanceof DruidDataSource){ DruidDataSource druidDataSource = (DruidDataSource) this.datasource; judgeDriver(druidDataSource.getDriverClassName()); } if (datasource instanceof ComboPooledDataSource){ ComboPooledDataSource comboPooledDataSource = (ComboPooledDataSource) this.datasource; judgeDriver(comboPooledDataSource.getDriverClass()); } } /** * 根据驱动判断是mysql/oracle的.sql文件 * @param driverClassName 驱动名称 */ private void judgeDriver(String driverClassName) throws SQLException, IOException { if (driverClassName.equals("com.mysql.jdbc.Driver") || driverClassName.equals("com.mysql.cj.jdbc.Driver")){ executeSqlFile("mysql"); } if (driverClassName.equals("oracle.jdbc.OracleDriver") || driverClassName.equals("oracle.jdbc.driver.OracleDriver")){ executeSqlFile("oracle"); } } /** * 执行sql文件 * @param dbname mysql/oracle */ private void executeSqlFile(String dbname) throws SQLException, IOException { File file = ResourceUtils.getFile("classpath:db"+File.separator+dbname); if (!file.exists()){ System.out.println("不存在【 "+"classpath:db"+File.separator+dbname+"】文件"); return; } File[] files = file.listFiles(); if (dbname.equals("oracle")){ for (File f : files){ String sqlRelativePath = "classpath:db"+File.separator+dbname+File.separator+f.getName(); Resource resource = springContextGetter.getApplicationContext().getResource(sqlRelativePath); //一条sql语句以"$$"结尾区分.执行oralce的存储过程 将'declare countCol number;'当初一条sql执行爆错,因默认以";"结尾是一条sql语句,更改成以"$$"分割作为一条sql语句 ScriptUtils.executeSqlScript(this.datasource.getConnection(), new EncodedResource(resource,"UTF-8"), false, false, "--", "$$", "/*", "*/"); System.out.println("执行: "+dbname+"/"+f.getName()); } } if (dbname.equals("mysql")){ for (File f : files){ String sqlRelativePath = "classpath:db"+File.separator+dbname+File.separator+f.getName(); Resource resource = springContextGetter.getApplicationContext().getResource(sqlRelativePath); //一条sql语句,默认以";"结尾区分 ScriptUtils.executeSqlScript(this.datasource.getConnection(), new EncodedResource(resource,"UTF-8")); System.out.println("执行: "+dbname+"/"+f.getName()); } } } } /** * Date: 2019-12-04 13:18 * Author: zhengja * Email: [email protected] * Desc:在初始化Bean时,操作数据库执行sql文件 */ @Component public class InitSql implements InitializingBean { @Value("${jdbc.isStartSql}") private boolean isStartSql; @Autowired private SchemaHandler schemaHandler; @Override public void afterPropertiesSet() throws Exception { if (isStartSql){ this.schemaHandler.execute(); } } } ``` **接口测试:** - 1、直接使用浏览器调用接口传参 - 2、使用postman工具 - 3、使用swagger api 测试(此项目引入了swagger) **druid测试:** - 访问:http://localhost:8080/项目路径/druid/index.html **到此所有的配置已完成!** 下面时配置文件的完整版! ## pom.xml 完整配置 ```xml 4.0.0 com.zja spring5x-mybatis-druid-base war spring5x-mybatis-druid-base 5.0.9.RELEASE 1.8 UTF-8 3.6.0 2.19.1 2.6 4.0.1 2.9.2 org.springframework spring-core ${spring.version} org.springframework spring-context ${spring.version} org.springframework spring-web ${spring.version} org.springframework spring-oxm ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-aop ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-beans ${spring.version} org.springframework spring-test ${spring.version} test javax.servlet javax.servlet-api ${servlet.version} provided com.fasterxml.jackson.core jackson-core 2.9.4 com.fasterxml.jackson.core jackson-databind 2.9.4 jackson-annotations com.fasterxml.jackson.core com.fasterxml.jackson.core jackson-annotations 2.9.4 org.slf4j slf4j-nop 1.7.28 io.springfox springfox-swagger2 ${springfox.version} jackson-annotations com.fasterxml.jackson.core spring-context org.springframework spring-beans org.springframework spring-aop org.springframework slf4j-api org.slf4j io.springfox springfox-swagger-ui ${springfox.version} mysql mysql-connector-java 8.0.13 com.oracle ojdbc6 11.2.0.3 com.alibaba druid 1.1.20 org.mybatis mybatis-spring 2.0.2 org.mybatis mybatis 3.5.2 com.github.pagehelper pagehelper 5.1.2 spring5x-mybatis-druid-base maven-compiler-plugin ${maven.compiler.plugin.version} ${jdk.version} ${jdk.version} ${project.build.sourceEncoding} maven-surefire-plugin ${mavne.surefire.plugin.version} true ``` spring-mvc.xml 完整配置 ```xml application/json;charset=UTF-8 text/html;charset=UTF-8 text/json;charset=UTF-8 ``` web.xml 完整配置 ```xml springMvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:META-INF/spring/spring-mvc.xml 1 springMvc / DruidStatView com.alibaba.druid.support.http.StatViewServlet resetEnable true loginUsername druid loginPassword druid DruidStatView /druid/* DruidWebStatFilter com.alibaba.druid.support.http.WebStatFilter exclusions *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* DruidWebStatFilter /* encoding org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true encoding /* ``` **完整配置已发完!** 1、druid测试: - 访问:http://localhost:8080/项目路径/druid/index.html 2、swagger api接口访问测试: - 访问:http://localhost:8080/项目路径/swagger-ui.html ## github 地址: * [https://github.com/zhengjiaao/spring5x](https://github.com/zhengjiaao/spring5x) ## 博客地址 * :https://www.jianshu.com/u/70d69269bd09 * 掘金: https://juejin.im/user/5d82daeef265da03ad14881b/posts

你可能感兴趣的:(spring5x-mybatis-base)