1. pom.xml
包含了mybatis代码生成插件,c3p0连接池
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itcuc</groupId>
<artifactId>qaserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>qaserver</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 數據庫連接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 创建数据库user表
CREATE TABLE `t_sys_user` (
`id` char(36) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`mobile` varchar(11) DEFAULT NULL,
`login_ip` varchar(255) DEFAULT NULL,
`login_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`is_aviliable` tinyint(4) DEFAULT NULL,
`type` int(2) DEFAULT NULL,
`avatar` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `username` (`username`) USING HASH,
KEY `email` (`email`),
KEY `mobile` (`mobile`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
不需要的字段可以酌情删除,实际上可以只保留username和password字段
3. 创建generatorConfig.xml 用于自动生成mapper文件和模型
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="C:\Users\Emily\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/qa" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.itcuc.qaserver.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.itcuc.qaserver.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="t_sys_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
运行一下插件就可以生成代码了
4. 加入启动类
package com.itcuc.qaserver;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootApplication
@MapperScan("com.itcuc.qaserver.mapper")
public class QaserverApplication {
public static void main(String[] args) {
SpringApplication.run(QaserverApplication.class, args);
}
}
5. 配置application.properties
server.port=8080
spring.datasource.name=qadata
spring.datasource.url=jdbc:mysql://localhost:3306/qa
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=100
spring.datasource.maxOpenPreparedStatements=20
mybatis.type-aliases-package=com.itcuc.qaserver.model
mybatis.mapper-locations=classpath:mapping/*.xml
6. 创建DataSource和Sessionfactory
DataSourceConfiguration 类配置c3p0数据源
SessionFactoryConfiguration 类配置SqlSessionFactory
@SpringBootConfiguration
public class DataSourceConfiguration {
@Value("${spring.datasource.driver-class-name}")
private String jdbcDriver;
@Value("${spring.datasource.url}")
private String jdbcUrl;
@Value("${spring.datasource.username}")
private String jdbcUser;
@Value("${spring.datasource.password}")
private String jdbcPassword;
@Value("${spring.datasource.maxActive}")
private Integer maxPoolSize;
@Value("${spring.datasource.maxWait}")
private Integer maxIdleTime;
@Value("${spring.datasource.minIdle}")
private Integer minPoolSize;
@Value("${spring.datasource.poolPreparedStatements}")
private Integer maxStatements;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private Integer idleConnectionTestPeriod;
@Value("${spring.datasource.validationQuery}")
private String preferredTestQuery;
@Value("${spring.datasource.testOnBorrow}")
private Boolean testConnectionOnCheckin;
@Value("${spring.datasource.testOnReturn}")
private Boolean testConnectionOnCheckout;
@Bean
public DataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUser);
dataSource.setPassword(jdbcPassword);
dataSource.setMaxPoolSize(maxPoolSize);
dataSource.setMaxIdleTime(maxIdleTime);
dataSource.setMinPoolSize(minPoolSize);
dataSource.setMaxStatementsPerConnection(maxStatements);
dataSource.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
dataSource.setPreferredTestQuery(preferredTestQuery);
dataSource.setTestConnectionOnCheckin(testConnectionOnCheckin);
dataSource.setTestConnectionOnCheckout(testConnectionOnCheckout);
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
@SpringBootConfiguration
public class SessionFactoryConfiguration {
@Value("${mybatis.mapper-locations}")
private String mapperXMLConfigPath;
@Value("${mybatis.type-aliases-package}")
private String mapperPackagePath;
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactoryBean createSqlSessionFactory() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageXMLConfigPath = mapperXMLConfigPath;
// 设置mapper 对应的XML 文件的路径
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageXMLConfigPath));
// 设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
// 设置mapper 接口所在的包
sqlSessionFactoryBean.setTypeAliasesPackage(mapperPackagePath);
return sqlSessionFactoryBean;
}
}
7. 创建一个简单的api
@RestController
@RequestMapping("/api/index")
public class IndexController {
@GetMapping("hello")
public String hello() {
return "hello";
}
}
使用crap测试接口
参考感谢: