一、项目简述
1. 开发工具:IDEA
2. 框架:SpringBoot + tk.Mybatis + Maven ,并集成JSP页面。
3. 本项目只是一个简单的demo,里面进行了基础的视图解析测试、JSON数据测试、数据库连接测试、log日志打印以及TK.Mybatis插件自动生成PO类、Mapper接口和对应的xml文件。
二、项目搭建
第一部分:创建项目
1. File-->New-->Project..-->Spring Initializr-->Next-->Next
2. 此时处于依赖选择这一步,本项目所选择的依赖如下:
Core:Lombok(把属性字段的set和get方法注解化)
Web:Web
SQL:MySQL、Mybatis
3. 选择完依赖后,点击Next-->Finish。此时一个SpringBoot框架的雏形就出来了。
4. 此时搭建的SpringBoot框架,是没有webapp这个模块的,需要手动添加配置,具体步骤在文章的第四部分有叙述。
第二部分:完善项目配置
1. 完善pom.xml文件【此处把本项目中所用的依赖提前粘出来】
<?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.iyungu</groupId>
<artifactId>phantaci</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>phantaci</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--springboot集成jsp相关依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--lombok注解-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--tk.mybatis相关依赖-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--logger日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!-- 添加该jar, 解决MyBaits 无法打印sql语句到控制台, -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>
</dependencies>
<build>
<!--配置以便编译xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.5.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
2. application.properties配置
#数据库配置
spring.datasource.url=jdbc:mysql://192.168.80.186:3306/bissv100
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
# mybatis配置
mybatis.typeAliasesPackage=com.iyungu.phantaci.po
mybatis.mapperLocations=classpath:com/iyungu/phantaci/mapper/*.xml
#demo-two项目名
server.servlet.context-path=/demo-two
#服务IP
server.port=8080
#视图解析器
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
3. generatorConfig.xml【tk.mybatis插件自动生成】
<?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>
<properties resource="application.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="autoDelimitKeywords" value="true"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.iyungu.phantaci.util.MyMapper"/>
</plugin>
<jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}">
</jdbcConnection>
<!--PO类所在位置-->
<javaModelGenerator targetPackage="com.iyungu.phantaci.po" targetProject="src/main/java"/>
<!--xml文件所在位置-->
<sqlMapGenerator targetPackage="com.iyungu.phantaci.mapper" targetProject="src/main/java"/>
<!--Dao接口所在位置-->
<javaClientGenerator targetPackage="com.iyungu.phantaci.dao" targetProject="src/main/java" type="XMLMAPPER"/>
<table schema="DEMO-TWO-TEST" tableName="u_user">
<!--mysql 配置-->
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
<!--oracle 配置-->
<!--<generatedKey column="id" sqlStatement="select SEQ_{1}.nextval from dual" identity="false" type="pre"/>-->
</table>
</context>
</generatorConfiguration>
使用方法:打开Maven Projects-->点击自己的项目-->Plugins-->点击mybatis-generator-->即可生成PO,Mapper接口及对应的XML。
第三部分:部分代码
1. Controller层
package com.iyungu.phantaci.controller;
import com.iyungu.phantaci.enums.ExceptionCode;
import com.iyungu.phantaci.po.UUser;
import com.iyungu.phantaci.service.HelloService;
import com.iyungu.phantaci.vo.Message;
import com.iyungu.phantaci.vo.ResponseUtil;
import com.iyungu.phantaci.vo.test.People;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author: Wang Yarui
* @Description:
* @Date: Created in 10:40 2018/6/27
* @Modified By:
*/
@Controller
@RequestMapping("/ph")
public class Hello {
private static final Logger logger = Logger.getLogger(Hello.class);
@Autowired
private HelloService helloService;
/**
* @Author: wangyarui@iyungu.com
* @Description:测试视图解析器
* @Date: Created in 10:43 2018/6/27
* @Param:
* @Return:
*/
@GetMapping(value = "/showHello")
public String showHello(String name) {
if (name == null) {
return "test/hello";
}
return "test/succ";
}
/**
* @Author: wangyarui@iyungu.com
* @Description:测试JSON数据
* @Date: Created in 9:38 2018/7/2
* @Param:
* @Return:
*/
@GetMapping(value = "/testJson")
@ResponseBody
public Message testJson() {
People people = new People();
return ResponseUtil.responseBody(people);
}
/**
* @Author: wangyarui@iyungu.com
* @Description:测试数据库是否正常连接
* @Date: Created in 9:39 2018/7/2
* @Param:
* @Return:
*/
@GetMapping(value = "/getUserInfoById")
@ResponseBody
public Message getUserInfoById(Long userId) {
logger.debug(String.format("getUserInfoById()方法开始执行,参数userId:{%s}",userId));
if (userId == null) {
return ResponseUtil.reponseBody(ExceptionCode.REQUEST_PARAM_ERROR.getCode(),ExceptionCode.REQUEST_PARAM_ERROR.getMsg());
}
UUser user = helloService.getUserInfoById(userId);
logger.debug("getUserInfoById()方法结束执行");
return ResponseUtil.responseBody(user);
}
/**
* @Author: wangyarui@iyungu.com
* @Description:测试Logger日志
* @Date: Created in 9:51 2018/7/3
* @Param:
* @Return:
*/
@GetMapping("/testLoggerInfo")
@ResponseBody
public Message getLoggerInfo(int num) {
logger.debug(String.format("getLoggerInfo()方法开始执行,参数num:{%s}",num));
int result = 0;
try {
result = 5/num;
} catch (Exception e) {
logger.error("分母不能为0",e);
e.printStackTrace();
}
logger.debug("getLoggerInfo()方法结束执行");
return ResponseUtil.responseBody(result);
}
/**
* @Author: wangyarui@iyungu.com
* @Description:获取用户姓名(测试sql打印及tk.mybaits的mapper扫描)
* @Date: Created in 11:22 2018/7/3
* @Param: [userId]
* @Return: com.iyungu.phantaci.vo.Message
*/
@GetMapping("/testLoggerSql")
@ResponseBody
public Message getUserName(Long userId) {
logger.debug(String.format("getUserName()开始执行,参数userId:{%s}",userId));
if (userId == null) {
logger.debug("无参数,getUserName()结束执行");
return ResponseUtil.reponseBody(ExceptionCode.REQUEST_PARAM_ERROR.getCode(),ExceptionCode.REQUEST_PARAM_ERROR.getCode());
}
String userName = helloService.getUserNameById(userId);
logger.debug("getUserName()结束执行");
return ResponseUtil.responseBody(userName);
}
}
2. config文件--->MybatisConfig
package com.iyungu.phantaci.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
public class MyBatisConfig {
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
try {
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
config文件--->MybatisMapperScannerConfig
package com.iyungu.phantaci.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
@Configuration
//必须在MyBatisConfig注册后再加载MapperScannerConfigurer,否则会报错
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.iyungu.phantaci.dao");
//初始化扫描器的相关配置,这里我们要创建一个Mapper的父类
Properties properties = new Properties();
properties.setProperty("mappers", "com.iyungu.phantaci.util.MyMapper");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
3. 注意:util文件--->MyMapper
package com.iyungu.phantaci.util;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//TODO
//FIXME 特别注意,该接口不能被扫描到,否则会出错
}
第四部分:补充
1. 缺少webapp模块
2.完整项目下载
3.项目目录