SpringBoot + Tk.Mybatis + Maven项目搭建(IDEA)

一、项目简述

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文件【此处把本项目中所用的依赖提前粘出来】



	4.0.0

	com.iyungu
	phantaci
	0.0.1-SNAPSHOT
	jar

	phantaci
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.3.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-actuator
			
				
					org.springframework.boot
					spring-boot-starter-logging
				
			
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
		
			org.apache.tomcat.embed
			tomcat-embed-jasper
		
		
			javax.servlet
			jstl
		
		
		
			org.projectlombok
			lombok
			true
		
		
		
			mysql
			mysql-connector-java
			5.1.6
		
		
		
			tk.mybatis
			mapper-spring-boot-starter
			2.0.0
		
		
		
			log4j
			log4j
			1.2.12
		
		
		
			org.slf4j
			slf4j-log4j12
			1.7.6
		
	

	
		
		
			
				src/main/java
				
					**/*.xml
				
			
		
		
			
				org.mybatis.generator
				mybatis-generator-maven-plugin
				1.3.5
				
					src/main/resources/generator/generatorConfig.xml
					true
					true
				
				
					
						mysql
						mysql-connector-java
						5.1.44
					
					
						tk.mybatis
						mapper
						3.5.2
					
				
			
		
	



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插件自动生成】





    

    
        
        
        

        
            
        

        
        

        
        
        
        
        
        

        
            
            
        

使用方法:打开Maven Projects-->点击自己的项目-->Plugins-->点击mybatis-generator-->即可生成PO,Mapper接口及对应的XML。

SpringBoot + Tk.Mybatis + Maven项目搭建(IDEA)_第1张图片


第三部分:部分代码

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: [email protected]
     * @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: [email protected]
     * @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: [email protected]
     * @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: [email protected]
     * @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: [email protected]
     * @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 extends Mapper, MySqlMapper {
    //TODO
    //FIXME 特别注意,该接口不能被扫描到,否则会出错
}

第四部分:补充

1.  缺少webapp模块

    解决方法:SpringBoot添加webapp目录

2.完整项目下载

    下载地址:点击此处下载完整项目

3.项目目录

SpringBoot + Tk.Mybatis + Maven项目搭建(IDEA)_第2张图片

你可能感兴趣的:(spring,boot)