使用springboot+springmvc+mybatis-generator开发web程序,也算是自己参考网上的知识自己写出来的吧,里面还很多东西值得深究学习
<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.0modelVersion>
<groupId>com.practicegroupId>
<artifactId>SSMartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.3.6.RELEASEversion>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<start-class>com.practice.Appstart-class>
<java.version>1.7java.version>
<lombok.version>1.14.8lombok.version>
<log4jdbc.log4j2.version>1.16log4jdbc.log4j2.version>
<rest.assured.version>2.3.3rest.assured.version>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.3version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.3version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.26version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>com.h2databasegroupId>
<artifactId>h2artifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.bgee.log4jdbc-log4j2groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1artifactId>
<version>${log4jdbc.log4j2.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<version>1.3.6.RELEASEversion>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.jayway.restassuredgroupId>
<artifactId>rest-assuredartifactId>
<version>${rest.assured.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.2.7.RELEASEversion>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.21version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-autoconfigureartifactId>
<version>1.3.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>4.1.6version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.3version>
<configuration>
<verbose>trueverbose>
<overwrite>trueoverwrite>
configuration>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
dependencies>
plugin>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>springloadedartifactId>
<version>${spring-loaded.version}version>
dependency>
dependencies>
plugin>
plugins>
build>
project>
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;
@Override
public 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;
}
@Bean
public 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();
}
@Bean
public 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"));
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:
<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" />
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
commentGenerator>
<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 {
@Autowired
private UserMapper userMapper;
@Override
public 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 {
@Autowired
private 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);
}
}