Spring Boot + Mybatis + Ehcache架构基本配置
2017-09-13 10:50
761 查看
1、基于springboot-1.4.0.RELEASE版本测试
2、springBoot + Mybatis + Ehcache + Druid + Mysql + servlet(jsp)
不废话,直接上代码
标准的maven项目结构,其中java下是
resources下存放mybatis的配置文件和Mapper.xml, 还有ehcache的配置文件
三、resources下的应用配置文件
四、启动应用主类文件
若需要部署到外部的tomcat容器中,则添加下面类即可。
springboot里默认使用tomcat的上传文件大小限制,即1MB,
修改用下面的配置类:
2、 配置web访问的servlet
这样启动项目后在浏览器中输入
扫描类配置
至此,所有的配置已完成,下面是一个操作数据的简单demo
Mapper.xml文件
十四、补上
至此配置全部完成,细节有时间再补充
关于生产mybatis配置文件的文章可以看:
[利用mybatis-generator自动生成代码 - JAVA_HIGHNESS的专栏 - 博客频道 - CSDN.NET]
(http://blog.csdn.net/javahighness/article/details/47704493)
2、springBoot + Mybatis + Ehcache + Druid + Mysql + servlet(jsp)
不废话,直接上代码
一、maven的pom文件
<?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.zsx</groupId> <artifactId>demo</artifactId> <packaging>war</packaging> <version>0.0.1</version> <name>zsx Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.7</jdk.version> <!-- 依赖版本 --> <tomcat.version>7.0.69</tomcat.version> <mybatis.version>3.4.1</mybatis.version> <mybatis.spring.version>1.3.0</mybatis.spring.version> <pagehelper.version>4.1.6</pagehelper.version> <fastjson.version>1.2.16</fastjson.version> <druid.version>1.0.25</druid.version> <apache.poi.version>3.14</apache.poi.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <dependencies> <!-- 添加对jsp视图解析的支持 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <!-- <version>7.0.69</version> --> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- 支持 Web 应用开发 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- 只需引入spring-boot-devtools 即可实现热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- 添加缓存支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- 使用ehcache缓存方案 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <!-- Spring Boot JDBC 与数据库操作相关的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mysql数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- MyBatis 分页插件 PageHelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!-- Json包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- 为了监控数据库 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- 导出excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${apache.poi.version}</version> </dependency> <!-- Junit 单元测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Swagger support --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.0</version> </dependency> </dependencies> <build> <finalName>/</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <dependencies> <!-- 热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.6.RELEASE</version> </dependency> </dependencies> </plugin> </plugins> </build> <repositories> <repository> <id>ali</id> <name>ali Repository</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
二、项目架构
想想还是介绍一下项目的目录结构,这样方便梳理整体的架构配置│ pom.xml ├─src │ ├─main │ │ ├─java │ │ │ └─com │ │ │ └─zsx │ │ │ │ Application.java │ │ │ │ SpringBootStartApplication.java │ │ │ │ │ │ │ ├─config │ │ │ │ │ DruidDBConfig.java │ │ │ │ │ MyStartupRunner.java │ │ │ │ │ │ │ │ │ ├─cache │ │ │ │ │ CacheConfiguration.java │ │ │ │ │ CacheUtil.java │ │ │ │ │ │ │ │ │ ├─filter │ │ │ │ │ DruidStatFilter.java │ │ │ │ │ │ │ │ │ ├─interceptors │ │ │ │ │ AuthInterceptor.java │ │ │ │ │ WebAppConfigurer.java │ │ │ │ │ │ │ │ │ ├─mybatis │ │ │ │ │ MybatisConfiguration.java │ │ │ │ │ MyBatisMapperScannerConfig.java │ │ │ │ │ │ │ │ │ ├─servlet │ │ │ │ │ DruidStatViewServlet.java │ │ │ │ │ │ │ │ │ └─swagger │ │ │ │ Swagger2.java │ │ │ │ │ │ │ ├─controller │ │ │ │ │ TestController.java │ │ │ │ │ │ │ ├─dao │ │ │ │ TuserMapper.java │ │ │ │ │ │ │ ├─entity │ │ │ │ ├─oa │ │ │ │ │ Tuser.java │ │ │ │ │ │ │ ├─model │ │ │ │ │ UserModel.java │ │ │ │ │ │ │ │ │ └─json │ │ │ │ JsonModel.java │ │ │ │ │ │ │ ├─service │ │ │ │ │ UserService.java │ │ │ │ │ │ │ │ │ └─impl │ │ │ │ UserServiceImpl.java │ │ │ │ │ │ │ └─util │ │ │ GlobalConstant.java │ │ │ │ │ ├─resources │ │ │ │ application.yml │ │ │ │ ehcache.xml │ │ │ │ │ │ │ ├─mybatis │ │ │ │ │ mybatis-config.xml │ │ │ │ │ │ │ │ │ └─mapper │ │ │ │ TuserMapper.xml │ │ │ │ │ │ │ └─static │ │ │ ├─css │ │ │ ├─img │ │ │ └─js │ │ │ │ │ └─webapp │ │ │ index.jsp │ │ │ │ │ └─WEB-INF │ │ │ web.xml │ │ │ │ │ └─view │ │ │ login.jsp │ │ │ │ │ ├─error │ │ │ 500.jsp │ │ │ └─test │ └─java │ UtilTest.java │
标准的maven项目结构,其中java下是
dao、
service、
controller,还有实体类映射
entity,其他配置
config
resources下存放mybatis的配置文件和Mapper.xml, 还有ehcache的配置文件
三、resources下的应用配置文件application.yml
#server: # port: 9090 spring: datasource: name: test url: jdbc:mysql://localhost:3306/test username: root password: root # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat # 初始化大小,最小,最大 initialSize: 5 minIdle: 5 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # HTTP ENCODING http: encoding.charset: UTF-8 encoding.enable: true encoding.force: true # view mvc: view: prefix: /WEB-INF/view/ suffix: .jsp # MyBatis mybatis: # 配置类型别名 typeAliasesPackage: com.zsx.entity # dao层接口 basePackage: com.zsx.dao # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath:mybatis/mapper/*.xml # 加载全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml # LOGGING logging: level: com.zsx.dao: DEBUG
四、启动应用主类文件
Application.java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @SpringBootApplication @ComponentScan // 开启通用注解扫描 @ServletComponentScan // 扫描使用注解方式的servlet public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
若需要部署到外部的tomcat容器中,则添加下面类即可。
package com.zsx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法 * @author ZSX * */ public class SpringBootStartApplication extends SpringBootServletInitializer { private static final Logger logger = LoggerFactory.getLogger(SpringBootStartApplication.class); @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
五、数据库连接池Druid的配置
package com.zsx.config; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; /** * DruidDBConfig类被@Configuration标注,用作配置信息; * DataSource对象被@Bean声明,为Spring容器所管理, * @Primary表示这里定义的DataSource将覆盖其他来源的DataSource。 * @author ZSX *jdbc.url=${jdbc.url} *最新的支持方式如下: *jdbc.url=@jdbc.url@ */ @Configuration public class DruidDBConfig { // private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class); @Value("${spring.datasource.url}") private String dbUrl; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.initialSize}") private int initialSize; @Value("${spring.datasource.minIdle}") private int minIdle; @Value("${spring.datasource.maxActive}") private int maxActive; @Value("${spring.datasource.maxWait}") private int maxWait; @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.validationQuery}") private String validationQuery; @Value("${spring.datasource.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.testOnReturn}") private boolean testOnReturn; @Value("${spring.datasource.poolPreparedStatements}") private boolean poolPreparedStatements; @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}") private String filters; @Value("{spring.datasource.connectionProperties}") private String connectionProperties; @Bean // 声明其为Bean实例 @Primary // 在同样的DataSource中,首先使用被标注的DataSource public DataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); // configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (SQLException e) { } datasource.setConnectionProperties(connectionProperties); return datasource; } }
springboot里默认使用tomcat的上传文件大小限制,即1MB,
修改用下面的配置类:
import javax.servlet.MultipartConfigElement; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MultipartConfig { @Bean public MultipartConfigElement multipartConfigElement(){ MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("10MB"); factory.setMaxRequestSize("10MB"); return factory.createMultipartConfig(); } }
六、开启Druid的数据库监控配置
1、配置Filterimport javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import com.alibaba.druid.support.http.WebStatFilter; /** * 配置druid监控统计功能 * 配置Filter * @author ZSX * */ @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = { @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源 } ) public class DruidStatFilter extends WebStatFilter { }
2、 配置web访问的servlet
import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import com.alibaba.druid.support.http.StatViewServlet; /** * 配置druid监控统计功能 * 在SpringBoot项目中基于注解的配置,如果是web.xml配置,按规则配置即可 * @author ZSX * */ @WebServlet(urlPatterns = "/druid/*", initParams = { // @WebInitParam(name = "allow", value = "192.168.16.110,127.0.0.1"), // IP白名单 (没有配置或者为空,则允许所有访问) // @WebInitParam(name="deny",value="192.168.16.111"), // IP黑名单 (存在共同时,deny优先于allow) @WebInitParam(name="loginUsername",value="druid"),// 用户名 @WebInitParam(name="loginPassword",value="druid"),// 密码 @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 } ) public class DruidStatViewServlet extends StatViewServlet { }
这样启动项目后在浏览器中输入
地址:端口/druid,就可以看到druid的监控web页面了
七、 拦截器配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebAppConfigurer extends WebMvcConfigurerAdapter { /** * 配置拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub // 多个拦截器组成一个拦截器链 // addPathPatterns 用于添加拦截规则 // excludePathPatterns 用户排除拦截 registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } /** * 添加自定义的静态资源映射 这里使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry.addResourceHandler("/new/**").addResourceLocations("classpath:/new/"); // registry.addResourceHandler("/**").addResourceLocations("/"); super.addResourceHandlers(registry); } }
八、swagger发布api测试配置(可忽略)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.zsx.controller.api")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("描述") .termsOfServiceUrl("http://zsx.com.cn") .version("1.0") .build(); } }
九、Mybatis配置
configuration的配置package com.zsx.config.mybatis; import java.io.IOException; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; 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.transaction.annotation.TransactionManagementConfigurer; @Configuration @EnableTransactionManagement public class MybatisConfiguration implements TransactionManagementConfigurer{ private static Log logger = LogFactory.getLog(MybatisConfiguration.class); // 配置类型别名 @Value("${mybatis.typeAliasesPackage}") private String typeAliasesPackage; // 配置mapper的扫描,找到所有的mapper.xml映射文件 @Value("${mybatis.mapperLocations}") private String mapperLocations; // 加载全局的配置文件 @Value("${mybatis.configLocation}") private String configLocation; @Autowired private DataSource dataSource; // DataSource配置 // @Bean // @ConfigurationProperties(prefix = "spring.datasource") // public DruidDataSource dataSource() { // return new com.alibaba.druid.pool.DruidDataSource(); // } // 提供SqlSeesion @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { try { SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); // 读取配置 sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage); Resource[] resources = new PathMatchingResourcePatternResolver() .getResources(mapperLocations); sessionFactoryBean.setMapperLocations(resources); sessionFactoryBean.setConfigLocation( new DefaultResourceLoader().getResource(configLocation)); return sessionFactoryBean.getObject(); } catch (IOException e) { logger.warn("mybatis resolver mapper*xml is error"); return null; } catch (Exception e) { logger.warn("mybatis sqlSessionFactoryBean create error"); return null; } } @Bean public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }
扫描类配置
package com.zsx.config.mybatis; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration //TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解 @AutoConfigureAfter({MybatisConfiguration.class}) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("com.zsx.dao"); return mapperScannerConfigurer; } }
十、Ehcache配置
resources目录下的ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <cache name="myCache" maxElementsInMemory="30" eternal="false" timeToIdleSeconds="1800" overflowToDisk="true" memoryStoreEvictionPolicy="LRU" /> </ehcache>
CacheConfiguration类
package com.zsx.config.cache; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; /** * * @author ZSX */ @Configuration @EnableCaching // 标注启动缓存 public class CacheConfiguration { /** * ehcache 主要的管理器 * @param bean * @return */ @Bean public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){ return new EhCacheCacheManager(bean.getObject()); } @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean(); factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); factoryBean.setShared(true); return factoryBean; } }
至此,所有的配置已完成,下面是一个操作数据的简单demo
十一、实体类 和 Mapper.xml 配置文件
实体类package com.zsx.entity.oa; import java.util.Date; public class Tuser { private Long id; private String userName; private String email; private String password; private String mobile; private String remark; private String nickName; private Integer userType; private Long personid; private Date register; private Integer delFlag; private Date createTime; private String creator; private Date updateTime; private String updator; private String isCheck; private String cardNo; private String workUnit; private String position; private String QQ; private String weixin; // getter setter 省略 }
Mapper.xml文件
resources\mybatis\mapper\TuserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zsx.dao.TuserMapper"> <resultMap id="BaseResultMap" type="com.zsx.entity.oa.Tuser"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="userName" jdbcType="VARCHAR" property="userName" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="mobile" jdbcType="VARCHAR" property="mobile" /> <result column="remark" jdbcType="VARCHAR" property="remark" /> <result column="nickName" jdbcType="VARCHAR" property="nickName" /> <result column="userType" jdbcType="INTEGER" property="userType" /> <result column="personid" jdbcType="BIGINT" property="personid" /> <result column="register" jdbcType="TIMESTAMP" property="register" /> <result column="delFlag" jdbcType="INTEGER" property="delFlag" /> <result column="createTime" jdbcType="TIMESTAMP" property="createTime" /> <result column="creator" jdbcType="VARCHAR" property="creator" /> <result column="updateTime" jdbcType="TIMESTAMP" property="updateTime" /> <result column="updator" jdbcType="VARCHAR" property="updator" /> <result column="isCheck" jdbcType="VARCHAR" property="isCheck" /> <result column="cardNo" jdbcType="VARCHAR" property="cardNo" /> <result column="workUnit" jdbcType="VARCHAR" property="workUnit" /> <result column="position" jdbcType="VARCHAR" property="position" /> <result column="QQ" jdbcType="VARCHAR" property="QQ" /> <result column="weixin" jdbcType="VARCHAR" property="weixin" /> </resultMap> <sql id="Base_Column_List"> id, userName, email, password, mobile, remark, nickName, userType, personid, register, delFlag, createTime, creator, updateTime, updator,isCheck,cardNo,workUnit,position,QQ,weixin </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_user where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from t_user where id = #{id,jdbcType=BIGINT} </delete> <insert id="insert" parameterType="com.zsx.entity.oa.Tuser"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into t_user (userName, email, password, mobile, remark, nickName, userType, personid, register, delFlag, createTime, creator, updateTime, updator,isCheck,cardNo,workUnit,position,QQ,weixin) values (#{userName,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}, #{nickName,jdbcType=VARCHAR}, #{userType,jdbcType=INTEGER}, #{personid,jdbcType=BIGINT}, #{register,jdbcType=TIMESTAMP}, #{delFlag,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{creator,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}, #{updator,jdbcType=VARCHAR}, #{isCheck,jdbcType=VARCHAR}, #{cardNo,jdbcType=VARCHAR} , #{workUnit,jdbcType=VARCHAR}, #{position,jdbcType=VARCHAR}, #{QQ,jdbcType=VARCHAR}, #{weixin,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.zsx.entity.oa.Tuser"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into t_user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userName != null"> userName, </if> <if test="email != null"> email, </if> <if test="password != null"> password, </if> <if test="mobile != null"> mobile, </if> <if test="remark != null"> remark, </if> <if test="nickName != null"> nickName, </if> <if test="userType != null"> userType, </if> <if test="personid != null"> personid, </if> <if test="register != null"> register, </if> <if test="delFlag != null"> delFlag, </if> <if test="createTime != null"> createTime, </if> <if test="creator != null"> creator, </if> <if test="updateTime != null"> updateTime, </if> <if test="updator != null"> updator, </if> <if test="isCheck != null"> isCheck, </if> <if test="cardNo != null"> cardNo, </if> <if test="workUnit != null"> workUnit, </if> <if test="position != null"> position, </if> <if test="QQ != null"> QQ, </if> <if test="weixin != null"> weixin, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="email != null"> #{email,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="mobile != null"> #{mobile,jdbcType=VARCHAR}, </if> <if test="remark != null"> #{remark,jdbcType=VARCHAR}, </if> <if test="nickName != null"> #{nickName,jdbcType=VARCHAR}, </if> <if test="userType != null"> #{userType,jdbcType=INTEGER}, </if> <if test="personid != null"> #{personid,jdbcType=BIGINT}, </if> <if test="register != null"> #{register,jdbcType=TIMESTAMP}, </if> <if test="delFlag != null"> #{delFlag,jdbcType=INTEGER}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="creator != null"> #{creator,jdbcType=VARCHAR}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="updator != null"> #{updator,jdbcType=VARCHAR}, </if> <if test="isCheck != null"> #{isCheck,jdbcType=VARCHAR}, </if> <if test="cardNo != null"> #{cardNo,jdbcType=VARCHAR}, </if> <if test="workUnit != null"> #{workUnit,jdbcType=VARCHAR}, </if> <if test="position != null"> #{position,jdbcType=VARCHAR}, </if> <if test="QQ != null"> #{QQ,jdbcType=VARCHAR}, </if> <if test="weixin != null"> #{weixin,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zsx.entity.oa.Tuser"> update t_user <set> <if test="userName != null"> userName = #{userName,jdbcType=VARCHAR}, </if> <if test="email != null"> email = #{email,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="mobile != null"> mobile = #{mobile,jdbcType=VARCHAR}, </if> <if test="remark != null"> remark = #{remark,jdbcType=VARCHAR}, </if> <if test="nickName != null"> nickName = #{nickName,jdbcType=VARCHAR}, </if> <if test="userType != null"> userType = #{userType,jdbcType=INTEGER}, </if> <if test="personid != null"> personid = #{personid,jdbcType=BIGINT}, </if> <if test="register != null"> register = #{register,jdbcType=TIMESTAMP}, </if> <if test="delFlag != null"> delFlag = #{delFlag,jdbcType=INTEGER}, </if> <if test="createTime != null"> createTime = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="creator != null"> creator = #{creator,jdbcType=VARCHAR}, </if> <if test="updateTime != null"> updateTime = #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="updator != null"> updator = #{updator,jdbcType=VARCHAR}, </if> <if test="isCheck != null"> isCheck = #{isCheck,jdbcType=VARCHAR}, </if> <if test="cardNo != null"> cardNo = #{cardNo,jdbcType=VARCHAR}, </if> <if test="workUnit != null"> workUnit = #{workUnit,jdbcType=VARCHAR}, </if> <if test="position != null"> position = #{position,jdbcType=VARCHAR}, </if> <if test="QQ != null"> QQ = #{QQ,jdbcType=VARCHAR}, </if> <if test="weixin != null"> weixin = #{weixin,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="com.zsx.entity.oa.Tuser"> update t_user set userName = #{userName,jdbcType=VARCHAR}, email = #{email,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, mobile = #{mobile,jdbcType=VARCHAR}, remark = #{remark,jdbcType=VARCHAR}, nickName = #{nickName,jdbcType=VARCHAR}, userType = #{userType,jdbcType=INTEGER}, personid = #{personid,jdbcType=BIGINT}, register = #{register,jdbcType=TIMESTAMP}, delFlag = #{delFlag,jdbcType=INTEGER}, createTime = #{createTime,jdbcType=TIMESTAMP}, creator = #{creator,jdbcType=VARCHAR}, updateTime = #{updateTime,jdbcType=TIMESTAMP}, updator = #{updator,jdbcType=VARCHAR}, isCheck = #{isCheck,jdbcType=VARCHAR}, cardNo = #{cardNo,jdbcType=VARCHAR}, workUnit = #{workUnit,jdbcType=VARCHAR}, position = #{position,jdbcType=VARCHAR}, QQ = #{QQ,jdbcType=VARCHAR}, weixin = #{weixin,jdbcType=VARCHAR} where id = #{id,jdbcType=BIGINT} </update> </mapper>
十二、dao层接口
package com.zsx.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.zsx.entity.oa.Tuser; public interface TuserMapper { int deleteByPrimaryKey(Long id); int insert(Tuser record); int insertSelective(Tuser record); Tuser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Tuser record); int updateByPrimaryKey(Tuser record); }
十三、service和controller没啥好说的,跟原先的一样,下面再提供一个单元测试的demo
import java.util.List; import javax.persistence.EntityManager; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.alibaba.fastjson.JSON; import com.zsx.Application; import com.zsx.dao.TuserMapper; import com.zsx.entity.pa.Tuser; @RunWith(SpringJUnit4ClassRunner.class) //指定我们SpringBoot工程的Application启动类 @SpringApplicationConfiguration(classes = Application.class) //由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration @WebAppConfiguration public class UtilTest { @Autowired private TuserMapper dao; @Test public void test1(){ dao.selectByPrimaryKey(1L); } @Test public void test2(){ // 分页助手 Page<Object> pageHelper = PageHelper.startPage(1, 10, true); List<Tuser> findAll = dao.findAll(); long total = pageHelper.getTotal(); // 总条数 int pages = pageHelper.getPages(); // 总页数 } }
十四、补上
mybatis-config.xml
配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties> <property name="dialect" value="mysql" /> </properties> <settings> <!-- 开启驼峰匹配 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 --> <setting name="cacheEnabled" value="true" /> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 --> <setting name="multipleResultSetsEnabled" value="true" /> <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 --> <setting name="useColumnLabel" value="true" /> <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如 Derby)。 系统默认值是false,设置只是为了展示出来 --> <setting name="useGeneratedKeys" value="false" /> <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 --> <setting name="defaultExecutorType" value="SIMPLE" /> <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <!-- 分页助手 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 数据库方言 --> <property name="dialect" value="mysql" /> <property name="offsetAsPageNum" value="true" /> <!-- 设置为true时,使用RowBounds分页会进行count查询 会去查询出总数 --> <property name="rowBoundsWithCount" value="true" /> <property name="pageSizeZero" value="true" /> <property name="reasonable" value="true" /> </plugin> </plugins> </configuration>
至此配置全部完成,细节有时间再补充
关于生产mybatis配置文件的文章可以看:
[利用mybatis-generator自动生成代码 - JAVA_HIGHNESS的专栏 - 博客频道 - CSDN.NET]
(http://blog.csdn.net/javahighness/article/details/47704493)
相关文章推荐
- Spring Boot + Mybatis + Ehcache 精准系统架构基本配置
- Spring Boot + Mybatis + Ehcache架构基本配置
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三十三)注解配置与EhCache使用(1)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三十四)注解配置与EhCache使用(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(二十七)使用MyBatis注解配置详解(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三)属性配置文件详解(1)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三)属性配置文件详解(1)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(四)属性配置文件详解(2)
- Spring Boot + Jpa(Hibernate) 架构基本配置
- Spring Boot + Jpa(Hibernate) 架构基本配置
- Spring Boot + Jpa(Hibernate) 架构基本配置详解
- Spring Boot + Jpa(Hibernate) 架构基本配置
- Spring Boot + Jpa(Hibernate) 架构基本配置
- Spring Cloud Spring Boot mybatis分布式微服务云架构(四)属性配置文件详解(2)
- Spring Boot + Jpa(Hibernate) 架构基本配置
- 基于springboot+mybatis的微信公众号开发第一篇-基本架构
- Spring Boot + Jpa(Hibernate) 架构基本配置
- [置顶] 基于springboot+mybatis的微信公众号开发第一篇-基本架构
- spring boot 整合mybatis、redis、 spring mvc基本配置
- Spring Cloud Spring Boot mybatis分布式微服务云架构(二十六)使用MyBatis注解配置详解(1)