springboot整合mybatis,druid,mybatis-generator插件完整版
一 springboot介绍
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是spring boot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架
二 springboot功能:
springboot其实就是简化开发的环境搭建,简单,方便,快捷;
在搭建传统项目时候,需要进行:
1 配置web.xml文件,去加载spring,springmvc的配置
2 加载数据库的连接,在xml文件中配置事务
3 开启注解配置,例如@reqestmapping,@Transactionnal等
4 开启tomcat或者jobss进行运行,配置tomcat的运行参数
那么有了springboot之后就不需要进行这么多的配置了,springboot的启动注解会帮助我们自动加载配置:
@SpringBootApplication这个是一个复合注解:
通过上面相信大家应该知道这个注解重要性了,接下来我们进行整合ssm,druid和自动生成代码插件了
三 整合步骤
1 首先需要在引入依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2 引入mybatis自动生成单表操作的插件
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> </dependencies> <executions> <execution> <id>mybatis generator</id> <phase>package</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!--允许移动生产的文件--> <verbose>true</verbose> <!--允许自动覆盖文件,在开发者不可以设置为true--> <overwrite>true</overwrite> <!--制定生产文件的位置--> <configurationFile> src/main/resources/mybatis_generator.xml </configurationFile> </configuration> </plugin> </plugins> </build>
3 yml文件配置:
# mybatis_config mybatis: mapper-locations: classpath:mapping/*.xml #datasource spring: datasource: druid: url: jdbc:mysql://localhost:3306/fr_db?allowMultiQueries=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull username: root password: 1234 driver-class-name: com.mysql.jdbc.Driver # 连接池配置 initial-size: 1 max-active: 20 min-idle: 1 max-wait: 10000 pool-prepared-statements: true max-open-prepared-statements: 20 validation-query: SELECT 1 FROM DUAL validation-query-timeout: 5000 test-on-borrow: false test-on-return: false test-while-idle: true time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 30000 max-evictable-idle-time-millis: 60000 removeAbandoned: true removeAbandonedTimeout: 1800 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 max-pool-prepared-statement-per-connection-size: 20 filters: stat,wall #filters: #配置多个英文逗号分隔(统计,sql注入,log4j过滤) type: com.alibaba.druid.pool.DruidDataSource
4 配置mybatis-generator.xml文件,
使用时候请注意上面注解的含义,需要更改包名,就是生成model,dao,xml文件的位置,避免出现问题,然后再配置表名,里面相关属性,可以选择,在这个模板下是不生成
带有example的实体类,和模糊条件查询的sql,因为在正式开发中都是通过ssql进行书写的,并不会使用example进行瓶装条件的
<?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> <!--驱动包的路径--> <!--<classPathEntry location="F:\maven\repos\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/>--> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--注释--> <commentGenerator> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> </commentGenerator> <!--数据库连接--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/fr_db?zeroDateTimeBehavior=convertToNull& autoReconnect=true&useUnicode=true&characterEncoding=utf-8" userId="root" password="1234"/> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--生成Model类存放位置--> <javaModelGenerator targetPackage="com.cxy.dataObject" targetProject="src/main/java"> <!--是否对model添加构造函数--> <property name="constructorBased" value="false"/> <!--是否允许子包--> <property name="enableSubPackages" value="true"/> <!--建立的model对象是否不可变,也就是生成的model没有setter方法--> <property name="immutable" value="false"/> <property name="trimStrings" value="false"/> </javaModelGenerator> <!--生成映射文件存放位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!--生成Mapper类存放位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.cxy.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!--生成与表对应的类名--> <table tableName="users" domainObjectName="UserDo" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
5 配至插件启动:
配置方式: 首先点击run,再进行edit configruation这个添加maven即可再添加如下内容,如果配置文件使用的是上面那个我的配置文件,可以直接使用图中命令
6 数据源配置:
package com.cxy.conf; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig { private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class); @Value("${spring.datasource.druid.url}") private String dbUrl; @Value("${spring.datasource.druid.username}") private String username; @Value("${spring.datasource.druid.password}") private String password; @Value("${spring.datasource.druid.driver-class-name}") private String driverClassName; @Value("${spring.datasource.druid.initial-size}") private int initialSize; @Value("${spring.datasource.druid.min-idle}") private int minIdle; @Value("${spring.datasource.druid.max-active}") private int maxActive; @Value("${spring.datasource.druid.max-wait}") private int maxWait; @Value("${spring.datasource.druid.time-between-eviction-runs-millis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.min-evictable-idle-time-millis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.druid.validation-query}") private String validationQuery; @Value("${spring.datasource.druid.test-while-idle}") private boolean testWhileIdle; @Value("${spring.datasource.druid.test-on-borrow}") private boolean testOnBorrow; @Value("${spring.datasource.druid.test-on-return}") private boolean testOnReturn; @Value("${spring.datasource.druid.pool-prepared-statements}") private boolean poolPreparedStatements; @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.druid.filters}") private String filters; @Value("{spring.datasource.druid.connection-properties}") private String connectionProperties; @Bean //声明其为Bean实例 @Primary //在同样的DataSource中,首先使用被标注的DataSource public DataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(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 (Exception e) { logger.error("druid configuration initialization filter", e); } datasource.setConnectionProperties(connectionProperties); return datasource; } @Bean public ServletRegistrationBean druidServlet() { //logger.info("init Druid Servlet Configuration "); ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); Map<String, String> initParameters = new HashMap<>(); /*initParameters.put("loginUsername", appConfig.getDruidUserName());// 用户名 initParameters.put("loginPassword", appConfig.getDruidPassword());// 密码 initParameters.put("resetEnable", appConfig.getDruidResetAll());// 禁用HTML页面上的“Reset All”功能*/ // initParameters.put("loginUsername", "druid");// 用户名 // initParameters.put("loginPassword", "druid");// 密码 initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能 initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问) // initParameters.put("deny", "192.168.20.38");// IP黑名单 initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问) //initParameters.put("deny", "192.168.20.38");// IP黑名单 (存在共同时,deny优先于allow) servletRegistrationBean.setInitParameters(initParameters); return servletRegistrationBean; } @Bean public FilterRegistrationBean druidWebStatViewFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter()); registrationBean.addInitParameter("urlPatterns", "/*"); registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); return registrationBean; } }
7 启动类配置
@SpringBootApplication @MapperScan("com.cxy.dao") public class DruidmybatisApplication { public static void main(String[] args) { SpringApplication.run(DruidmybatisApplication.class, args); } }
8 :编写controller进行数据访问:
package com.cxy.controller; import com.cxy.dao.UserDoMapper; import com.cxy.dataObject.UserDo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @CrossOrigin @RestController @RequestMapping("/user") public class UserController { @Autowired UserDoMapper userDoMapper; @RequestMapping(method = RequestMethod.GET) public UserDo getAllUserInfo(){ Long a=45L; return userDoMapper.selectByPrimaryKey(a); } @RequestMapping(value = "/all",method = RequestMethod.GET) public List<UserDo> getAllUserInfo2(){ //Long a=45L; return userDoMapper.getAllUserInfo(); } }
注:注解解释:
@CrossOrign 这个注解是解决跨域问题.
@RestController 这个注解等于 @Controller和@responseBody 就是表示为一个controller被spring管理,和返回数据为josn格式的
九 由于为了简单没有配置service层,是在controller中直接引入,启动项目:
9 项目访问
10 通过访问druid进行sql监控
访问路径为:http://localhost:8080/druid/sql.html
至此整合内容已经完成,但是会出现问题,mysql时区错误问题