使用maven+springboot+springmvc+mybaits-spring+mybatis-generator开发

本文主要是介绍使用maven+springboot+springmvc+mybaits-spring+mybatis-generator开发,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用springboot+springmvc+mybatis-generator开发web程序,也算是自己参考网上的知识自己写出来的吧,里面还很多东西值得深究学习
先看项目目录

  1. 使用IDEA和MAVEN新建springboot项目:具体怎么新建网上很多
    使用maven就看一下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.practice</groupId><artifactId>SSM</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.3.6.RELEASE</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><start-class>com.practice.App</start-class><java.version>1.7</java.version><lombok.version>1.14.8</lombok.version><log4jdbc.log4j2.version>1.16</log4jdbc.log4j2.version><rest.assured.version>2.3.3</rest.assured.version></properties><dependencies><!--MG依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.3</version><scope>test</scope></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.3</version><scope>test</scope></dependency><!--druid数据库连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.26</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!--springboot依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version><scope>provided</scope></dependency><dependency><groupId>org.bgee.log4jdbc-log4j2</groupId><artifactId>log4jdbc-log4j2-jdbc4.1</artifactId><version>${log4jdbc.log4j2.version}</version></dependency><!--springboottest依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- Springboot 热部署 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><version>1.3.6.RELEASE</version><optional>true</optional></dependency><dependency><groupId>com.jayway.restassured</groupId><artifactId>rest-assured</artifactId><version>${rest.assured.version}</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.2.7.RELEASE</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.21</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>1.3.6.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><!-- mybatis 分页插件 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>4.1.6</version></dependency></dependencies><build><plugins><!--MG的插件--><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.3</version><configuration><verbose>true</verbose><overwrite>true</overwrite></configuration><dependencies><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java配置这个依赖主要是为了等下在配置MG的时候可以不用配置classPathEntry这样的一个属性,避免代码的耦合度太高 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency></dependencies></plugin><!--springboot的插件--><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><dependencies><dependency><groupId>org.springframework</groupId><artifactId>springloaded</artifactId><version>${spring-loaded.version}</version></dependency></dependencies></plugin></plugins></build></project>
  1. 修改springboot的配置文件,这里一共有四个配置文件:application.properties(默认读取)、application-dev.properties(开发环境)、application-prod.properties(生成环境)、application-test.properties(测试环境)
    默认会读取resource目录下的application.properties,内容如下
spring.thymeleaf.cache=false
logging.level.jdbc=OFF
logging.level.jdbc.sqltiming=error
logging.level.jdbc.resultsettable=error
#申明使用哪个配置文件
spring.profiles.active=dev

通过spring.profiles.active=dev这个属性来控制具体使用哪个配置(dev,prod,test).
以application-dev.properties(开发环境)为例,配置如下:

#数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ssm
spring.datasource.username=root
spring.datasource.password=root
# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true#视图模型
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.check-template-location=true

主要是数据源的配置,这里使用druid数据源,然后通过DruidDataSourceConfig.java读取数据源的配置:

/*
* Copyright (c) 2016 www.bsfit.com.cn All Rights Reserved.
*/
package com.practice.cfg;import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;/*** @author: YeJunwei  Date: 2016/12/2 Time: 15:07*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "com.practice.mapper")
public class DruidDataSourceConfig implements EnvironmentAware {private Environment environment;private RelaxedPropertyResolver propertyResolver;@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");}//注册dataSource@Bean(initMethod = "init", destroyMethod = "close")public DruidDataSource dataSource() throws SQLException {if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) {System.out.println("Your database connection pool configuration is incorrect!"+ " Please check your Spring profile, current profiles are:"+ Arrays.toString(environment.getActiveProfiles()));throw new ApplicationContextException("Database connection pool is not configured correctly");}DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));druidDataSource.setUrl(propertyResolver.getProperty("url"));druidDataSource.setUsername(propertyResolver.getProperty("username"));druidDataSource.setPassword(propertyResolver.getProperty("password"));druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));druidDataSource.setFilters(propertyResolver.getProperty("filters"));return druidDataSource;}@Beanpublic SqlSessionFactory sqlSessionFactory() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource());//mybatis分页PageHelper pageHelper = new PageHelper();Properties props = new Properties();props.setProperty("dialect", "mysql");props.setProperty("reasonable", "true");props.setProperty("supportMethodsArguments", "true");props.setProperty("returnPageInfo", "check");props.setProperty("params", "count=countSql");pageHelper.setProperties(props); //添加插件sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/practice/sqlmap/*.xml"));return sqlSessionFactoryBean.getObject();}@Beanpublic PlatformTransactionManager transactionManager() throws SQLException {return new DataSourceTransactionManager(dataSource());}
}

这里因为后面要用到mybatis-generator和mybatise-spring集成所以需要sqlSession,这里比较重要的就是这里要指定使用的xml的位置和使用@MapperScan(value = “com.practice.mapper”)注解来扫描与xml相对应的mapper接口:

sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/practice/sqlmap/*.xml"));
  • 1

3,使用mybatis-generator自动生成代码,在pom文件中添加了MG的插件所以这里配置一下MG的配置文件就可以,放在resource目录下:generatorConfig.properties,generatorConfig.xml。
先新建user表:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` varchar(50) NOT NULL,`name` varchar(255) DEFAULT NULL,`age` int(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><properties resource="generatorConfig.properties"/><context id="ssm" targetRuntime="MyBatis3"><plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" /><plugin type="org.mybatis.generator.plugins.SerializablePlugin" /><plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" /><!-- <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> --><commentGenerator><property name="suppressDate" value="true" /><property name="suppressAllComments" value="true" /></commentGenerator><!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@10.100.1.20:1521:db1"userId="rams_test" password="bangsun"></jdbcConnection>--><jdbcConnection driverClass="${driver}"connectionURL="${url}" userId="${username}" password="${password}"></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><javaModelGenerator targetPackage="com.practice.pojo" targetProject="src/main/java"><property name="constructorBased" value="true" /><property name="enableSubPackages" value="true" /><property name="trimStrings" value="true" /></javaModelGenerator><sqlMapGenerator targetPackage="com.practice.sqlmap" targetProject="src/main/resources"><property name="enableSubPackages" value="true" /></sqlMapGenerator><javaClientGenerator type="XMLMAPPER" targetPackage="com.practice.mapper"targetProject="src/main/java"><property name="enableSubPackages" value="true" /></javaClientGenerator><table schema="mybatis" tableName="user" domainObjectName="User"><property name="constructorBased" value="true" /><property name="useActualColumnNames" value="false" /><property name="ignoreQualifiersAtRuntime" value="true" /></table></context>
</generatorConfiguration>

generatorConfig.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/ssm
username=root
password=root

这里写图片描述
配置好之后双击,就会在指定目录生成代码了。
这里写图片描述
然后就是编写controller和service了:
IUserService.java:

package com.practice.service;import com.practice.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;/*** @author: YeJunwei  Date: 2016/12/5 Time: 10:54*/
public interface IUserService {User getUserById(String id);
}

UserServiceImpl.java:

/*
* Copyright (c) 2016 www.bsfit.com.cn All Rights Reserved.
*/
package com.practice.service.impl;import com.practice.mapper.UserMapper;
import com.practice.pojo.User;
import com.practice.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;/*** @author: YeJunwei  Date: 2016/12/5 Time: 10:54*/
@Component
public class UserServiceImpl implements IUserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User getUserById(String id) {
//        UserExample example=new UserExample();
//        example.createCriteria().andIdEqualTo(id);User user=userMapper.selectByPrimaryKey(id);return user;}
}

UserController.java

/*
* Copyright (c) 2016 www.bsfit.com.cn All Rights Reserved.
*/
package com.practice.controller;import com.alibaba.fastjson.JSON;
import com.practice.pojo.User;
import com.practice.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;/*** @author: YeJunwei  Date: 2016/12/5 Time: 10:31*/
@RestController
public class UserController {@Autowiredprivate IUserService userService;@RequestMapping(value = "/user",method = RequestMethod.GET)public String getUserById(String id){User user=userService.getUserById(id);String userStr= JSON.toJSONString(user);return userStr;}
}

最后启动App.java
package com.practice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
这里写图片描述

这篇关于使用maven+springboot+springmvc+mybaits-spring+mybatis-generator开发的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1079741

相关文章

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

SpringBoot使用Apache Tika检测敏感信息

《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

Java内存泄漏问题的排查、优化与最佳实践

《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

Linux使用dd命令来复制和转换数据的操作方法

《Linux使用dd命令来复制和转换数据的操作方法》Linux中的dd命令是一个功能强大的数据复制和转换实用程序,它以较低级别运行,通常用于创建可启动的USB驱动器、克隆磁盘和生成随机数据等任务,本文... 目录简介功能和能力语法常用选项示例用法基础用法创建可启动www.chinasem.cn的 USB 驱动

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

使用SQL语言查询多个Excel表格的操作方法

《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3