spring-boot 注解配置mybatis+druid(新手上路)

转载 2016年12月20日 10:17:17
  • 10475

spring-boot 注解配置mybatis+druid(新手上路)

之前已经介绍了新手如何搭建一个简单的springboot,接下来介绍一下springboot+mybatis+druid的配置方法。

鄙人不才,参考了一些高手的博文以及官方文档,整理出了一点心得。

对高手的感谢无以言表,原文地址:http://blog.csdn.net/lxhjh/article/details/51764604

http://blog.csdn.net/xiaoyu411502/article/details/51392237

使用环境:JDK1.8 、eclipse-neon、maven3.5+、mysql5.5

框架使用:springboot1.4.1、druid1.0.26、mybatis自动获取版本号

介绍:我使用的配置文件格式为application.properties,基本都是使用注解的方式搭建。

数据库表结构,databases名为mydatabases;表明为city,字段有三个,分别是id、name、province,数据类型是varchar(20)。

第一步:

开始还是新建springboot项目,然后导包。

新建maven项目,选择jar包。

配置pom.xml文件。

  1. <properties>
  2. <java.version>1.8</java.version>
  3. </properties>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>1.4.1.RELEASE</version>
  8. </parent>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-web</artifactId>
  13. </dependency>
  14. <!-- druid数据库连接池 -->
  15. <dependency>
  16. <groupId>com.alibaba</groupId>
  17. <artifactId>druid</artifactId>
  18. <version>1.0.26</version>
  19. </dependency>
  20. <!-- springboot的mybatis -->
  21. <dependency>
  22. <groupId>org.mybatis.spring.boot</groupId>
  23. <artifactId>mybatis-spring-boot-starter</artifactId>
  24. <version>1.1.1</version>
  25. </dependency>
  26. <!-- MySql数据库驱动 -->
  27. <dependency>
  28. <groupId>mysql</groupId>
  29. <artifactId>mysql-connector-java</artifactId>
  30. </dependency>
  31. <!-- Springboot 热部署 -->
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-devtools</artifactId>
  35. <optional>true</optional>
  36. </dependency>
  37. </dependencies>

第二步:

创建启动类。

  1. import org.mybatis.spring.annotation.MapperScan;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.boot.web.servlet.ServletComponentScan;
  5. @SpringBootApplication
  6. @ServletComponentScan   //扫描Servlet
  7. @MapperScan("mapper")<span style="white-space:pre"> </span>//这里mapper是你的mybatis的mapper目录。
  8. public class Application {
  9. public static void main(String[] args) {
  10. SpringApplication.run(Application.class, args);
  11. }
  12. }

第三步:

填写配置文件。(这里呀,参数比较多,可以选择填写。)

我使用的是application.properties文件,该文件放在src/main/resources目录下,springboot框架启动后会自动读取它。

  1. #数据库设置
  2. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.driverClassName=com.mysql.jdbc.Driver
  4. spring.datasource.url=jdbc:mysql://localhost:3306/mydatabases
  5. spring.datasource.username=root
  6. spring.datasource.password=123
  7. #--------------------------
  8. # 下面为连接池的补充设置,应用到上面所有数据源中
  9. # 初始化大小,最小,最大
  10. spring.datasource.initialSize=5
  11. spring.datasource.minIdle=5
  12. spring.datasource.maxActive=20
  13. # 配置获取连接等待超时的时间
  14. spring.datasource.maxWait=60000
  15. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  16. spring.datasource.timeBetweenEvictionRunsMillis=60000
  17. # 配置一个连接在池中最小生存的时间,单位是毫秒
  18. spring.datasource.minEvictableIdleTimeMillis=300000
  19. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  20. spring.datasource.testWhileIdle=true
  21. spring.datasource.testOnBorrow=false
  22. spring.datasource.testOnReturn=false
  23. # 打开PSCache,并且指定每个连接上PSCache的大小
  24. spring.datasource.poolPreparedStatements=true
  25. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  26. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  27. spring.datasource.filters=stat,wall,log4j
  28. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  29. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  30. # 合并多个DruidDataSource的监控数据
  31. #spring.datasource.useGlobalDataSourceStat=true

第四步:

配置数据源。这里相关的参数会自动赋值到datasource里。

  1. import javax.sql.DataSource;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import com.alibaba.druid.pool.DruidDataSource;
  6. @Configuration
  7. public class DruidDataSourceConfiguration {
  8. @Bean
  9. @ConfigurationProperties(prefix = "spring.datasource")
  10. public DataSource druidDataSource() {
  11. DruidDataSource druidDataSource = new DruidDataSource();
  12. return druidDataSource;
  13. }
  14. }

第五步:

写一个实体类。这里可以随意哈。

  1. import java.io.Serializable;
  2. public class City implements Serializable{
  3. private static final long serialVersionUID = 1L;
  4. private String id;
  5. private String name;
  6. private String province;
  7. City(){
  8. }
  9. public String getId() {
  10. return id;
  11. }
  12. public void setId(String id) {
  13. this.id = id;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public String getProvince() {
  22. return province;
  23. }
  24. public void setProvince(String province) {
  25. this.province = province;
  26. }
  27. @Override
  28. public String toString() {
  29. return "City [id=" + id + ", name=" + name + ", province=" + province + "]";
  30. }
  31. }

第六步:

写mapper文件。这里的包地址为Application的MapperScan的值。

  1. import org.apache.ibatis.annotations.Param;
  2. import org.apache.ibatis.annotations.Select;
  3. public interface CityMapper {
  4. @Select("select * from city where id = #{id}")
  5. City findCityById(@Param("id") String id);
  6. }

第七步:

这里就不写Service了,直接在Controller里写了。

  1. import javax.annotation.Resource;
  2. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. @RequestMapping("/demo")
  8. @EnableAutoConfiguration
  9. public class HelloController {
  10. @Resource
  11. private CityMapper cityMapper;
  12. @RequestMapping("/test")
  13. String test1(){
  14. return "hello,test1()";
  15. }
  16. @RequestMapping("/findCity2")
  17. City findCity2(@RequestParam String id){
  18. return cityMapper.findCityById(id);
  19. }
  20. }

第八步:

这里要写filter,配合druid监控的使用。

  1. import javax.servlet.annotation.WebFilter;
  2. import javax.servlet.annotation.WebInitParam;
  3. import com.alibaba.druid.support.http.WebStatFilter;
  4. @WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
  5. initParams={
  6. @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
  7. }
  8. )
  9. public class DruidStatFilter extends WebStatFilter{
  10. }

第九步:

配置监控界面。

  1. import com.alibaba.druid.support.http.StatViewServlet;
  2. import javax.servlet.annotation.WebServlet;
  3. import javax.servlet.annotation.WebInitParam;
  4. @WebServlet(urlPatterns = "/druid/*",
  5. initParams={
  6. @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
  7. @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
  8. @WebInitParam(name="loginUsername",value="admin"),// 用户名
  9. @WebInitParam(name="loginPassword",value="123"),// 密码
  10. @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
  11. })
  12. public class DruidStatViewServlet extends StatViewServlet {
  13. private static final long serialVersionUID = 1L;
  14. }

第十步:

启动测试。在application.java中启动,浏览器中先进入:localhost:8080/druid/login.html,输入用户名:admin,密码:123,进入。

再执行一下localhost:8080/demo/findCity2?id=001,(你的数据)查看结果。这里需要你的数据库里有数据。

在监控页面看看sql监控是否被监控到。

附上源码:点击打开链接

肚子饿。。。

转-spring-boot 注解配置mybatis+druid(新手上路)-http://blog.csdn.net/sinat_36203615/article/details/53759935的更多相关文章

  1. Nginx 配置location root 转自https://blog.csdn.net/rofth/article/details/78581617

    nginx指定文件路径有两种方式root和alias,root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上. 最基本的区别 ...

  2. Spring配置xml自动提示——转载https://blog.csdn.net/sinat_18474835/article/details/79370629

    以Spring2.0为例: 下载地址: Csdn: http://download.csdn.net/download/hh775313602/9812757 没积分的可以去百度网盘下载,我已共享: ...

  3. OpenSessionInViewFilter 的配置及作用(原文地址: http://blog.csdn.net/sunsea08/article/details/4545186)

    spring为我们解决hibernate的Session的关闭与开启问题. Hibernate 允许对关联对象.属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Sessio ...

  4. Ubuntu 16.04安装JDK并配置环境变量(转发:https://blog.csdn.net/yan3013216087/article/details/78307258)

    系统版本:Ubuntu 16.04 JDK版本:jdk1.8.0_121 1.官网下载JDK文件jdk-8u121-linux-x64.tar.gz 我这里下的是最新版,其他版本也可以 2.创建一个目 ...

  5. 基于eclipse的mybatis映射代码自动生成的插件http://blog.csdn.net/fu9958/article/details/7521681

    基于eclipse的mybatis映射代码自动生成的插件 分类: JAVA 数据库 工具相关2012-04-29 00:15 2157人阅读 评论(9) 收藏 举报 eclipsegeneratori ...

  6. 使用Mybatis进行连表查询、left join---https://blog.csdn.net/jinzhencs/article/details/51980518

    使用Mybatis进行连表查询.left join https://blog.csdn.net/jinzhencs/article/details/51980518

  7. Spring Boot 注解配置 day03

    一.SpringBoot注解 @PropertySource 和 @ImportResource和@Bean 1.@PropertySource 加载指定位置的配置文件(只能是properties文件 ...

  8. Spring Boot下配置MyBatis多数据源

    http://m.blog.csdn.net/article/details?id=51481911

  9. 实例化Bean的方法(基于xml配置)-http://blog.csdn.net/shymi1991/article/details/48153293

    实例化Bean的方法(基于xml配置) 标签: spring framework 2015-09-01 13:43 918人阅读 评论(0) 收藏 举报  分类: Spring FrameWork(7 ...

随机推荐

  1. [Java代码] Java是自学好还是参加培训班好?

    ava 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言. Java可运行于多个平台,如Windows, Mac OS,及其他多种UNIX版本的系统. 本教程给大家简单介 ...

  2. 3-20 标准库:find库; 学习编程语言3节课(大多是旧识,全*栈)3-21 面向对象. Percent Strings; 元编程和Rails的相互理解

    Find The Find module supports the top-down traversal of a set of file paths.(一系列文件的路径的遍历) find(*path ...

  3. Confluence 6 自动添加用户到用户组

    默认组成员(Default Group Memberships) 选项在 Confluence 3.5 及后续版本和 JIRA 4.3.3 及后续版本中可用.这字段将会在你选择 'Read Only, ...

  4. struts2整合axis2后,访问不到wsdl,被struts2拦截的解决办法

    在struts2中整合axis2后,访问wsdl的时候显示404  not found There is no Action mapped for action name xxxxxxxx. 解决办法 ...

  5. map和unordered_map

    1.boost::unordered_map, 它与 stl::map的区别就是,stl::map是按照operator<比较判断元素是否相同,以及比较元素的大小,然后选择合适的位置插入到树中. ...

  6. close_on_exec标志位的作用

    转自:http://blog.csdn.net/sunlylorn/article/details/6363727 close_on_exec 是一个进程所有文件描述符(文件句柄)的位图标志,每个比特 ...

  7. mongodb控制台中文乱码

    问题描述: 使用命令行打开mongo,查询的结果里中文都是乱码,检查了文件编码均正常: 解决方法: 该问题是cmd字体引起的,设置cmd的字体即可,cmd的默认字体是“点阵字体”,选择其他两个均可,如 ...

  8. photoshop cc 智能切图

    这节分享一个photoshop cc 开始有的自动生成图标的方法 psd练习文件 http://pan.baidu.com/s/1pL2dwL1 1 工具:我这里用的是photoshop cc 201 ...

  9. hadoop mongodb install(3)

    reference:http://dblab.xmu.edu.cn/blog/868-2/ root@iZuf68496ttdogcxs22w6sZ:~# mv mongodb-linux-x86_6 ...

  10. 抓取错误之onerror

    一处定义,可以抓取全局的错误,相当于一个全局的try catch呀. <html> <head> <script type="text/javascript&q ...