一、环境:
IDE:IntelliJ IDEA 2017.1.1
JDK:1.8.0_161
Maven:3.3.9
springboot:2.0.2.RELEASE
二、说明:
本文综合之前的两篇博文,将mybatis、druid同时集成到spring boot框架,展示集成的步骤和效果。
三、步骤方法:
1.使用IntelliJ IDEA创建spring boot项目(过程略),创建后项目工程如下。
2.配置POM.xml
4.0.0 com.yy sbmybatisdruid 0.0.1-SNAPSHOT jar sbmybatisdruid Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web 2.0.2.RELEASE mysql mysql-connector-java 5.1.46 com.alibaba druid-spring-boot-starter 1.1.0 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools log4j log4j RELEASE org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.mybatis.generator mybatis-generator-maven-plugin 1.3.2 true true
3.application.properties
server.port=8888# 数据库访问配置spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&useSSL=falsespring.datasource.username=rootspring.datasource.password=mysql# 下面为连接池的补充设置,应用到上面所有数据源中spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4jspring.datasource.logSlowSql=true#设置热部署#开启热部署spring.devtools.restart.enabled=true#重启范围spring.devtools.restart.additional-paths=src/main/java #防止Invalid bound statement (not found)mybatis.mapper-locations= classpath:mapping/*.xml
4.配置mybatis
4.1自动生成generatorConfig.xml
4.2配置maven启动
启动mybatis自动生成mapper、model、mapping相关,
生成的Model(UserInfo.java),如下
package com.yy.entity;public class UserInfo { private Integer id; private String name; private Integer age; private Integer sex; private String province; private String city; private String job; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } public String getCity() { return city; } public void setCity(String city) { this.city = city == null ? null : city.trim(); } public String getJob() { return job; } public void setJob(String job) { this.job = job == null ? null : job.trim(); }}
生成的Mapper(UserInfoMapper),如下
package com.yy.mapper;import com.yy.entity.UserInfo;import org.springframework.stereotype.Repository;@Repositorypublic interface UserInfoMapper { int deleteByPrimaryKey(Integer id); int insert(UserInfo record); int insertSelective(UserInfo record); UserInfo selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(UserInfo record); int updateByPrimaryKey(UserInfo record);}
生成的Mapping(UserInfoMapper.xml)
id, name, age, sex, province, city, job delete from user_info where id = #{id,jdbcType=INTEGER} insert into user_info (id, name, age, sex, province, city, job) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{sex,jdbcType=INTEGER}, #{province,jdbcType=VARCHAR}, #{city,jdbcType=VARCHAR}, #{job,jdbcType=VARCHAR}) insert into user_info id, name, age, sex, province, city, job, #{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{sex,jdbcType=INTEGER}, #{province,jdbcType=VARCHAR}, #{city,jdbcType=VARCHAR}, #{job,jdbcType=VARCHAR}, update user_info where id = #{id,jdbcType=INTEGER} name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER}, sex = #{sex,jdbcType=INTEGER}, province = #{province,jdbcType=VARCHAR}, city = #{city,jdbcType=VARCHAR}, job = #{job,jdbcType=VARCHAR}, update user_info set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER}, sex = #{sex,jdbcType=INTEGER}, province = #{province,jdbcType=VARCHAR}, city = #{city,jdbcType=VARCHAR}, job = #{job,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER}
5.项目启动类,SbmybatisdruidApplication.java
package com.yy;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@SpringBootApplication//启动类中添加对mapper包扫描@MapperScan@MapperScan(value = "com.yy.mapper")public class SbmybatisdruidApplication { public static void main(String[] args) { SpringApplication.run(SbmybatisdruidApplication.class, args); }}
6.Druid数据源配置(DruidConfig.java)
package com.yy.config;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.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 javax.sql.DataSource;import java.sql.SQLException;/** * Created by Administrator on 2018-06-06. */@Configurationpublic class DruidConfig { private Logger logger = LoggerFactory.getLogger(DruidConfig.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.filters}") private String filters; @Value("${spring.datasource.logSlowSql}") private String logSlowSql; @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); reg.addInitParameter("loginUsername", username); reg.addInitParameter("loginPassword", password); reg.addInitParameter("logSlowSql", logSlowSql); return reg; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.addInitParameter("profileEnable", "true"); return filterRegistrationBean; } @Bean public DataSource druidDataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); 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); try { datasource.setFilters(filters); } catch (SQLException e) { logger.error("druid configuration initialization filter", e); } return datasource; }}
三、测试
3.1.编写Controller(HelloController.java)
package com.yy.controller;import com.yy.entity.UserInfo;import com.yy.mapper.UserInfoMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.ModelAndView;/** * Created by Administrator on 2018-06-06. */@RestController@RequestMapping(value="/users")public class HelloController { @Autowired UserInfoMapper userInfoMapper; @RequestMapping(value = "/getById/{id}") private ModelAndView getUserById(@PathVariable(value="id") Integer Id) { ModelAndView mv=new ModelAndView(); UserInfo userInfo= userInfoMapper.selectByPrimaryKey(Id); mv.addObject("userinfo",userInfo); mv.setViewName("index"); return mv; }}
问题一:
出现问题提示:Could not autowire. No beans of 'UserInfoMapper' type found. less... (Ctrl+F1) Checks autowiring problems in a bean class.
解决:UserInfoMapper类添加@Repository注解
问题二:
出现问题提示:Field userInfoMapper in com.yy.controller.HelloController required a bean of type 'com.yy.mapper.UserInfoMapper' that could not be found.
在启动类添加@MapperScan("com.yy.mapper")注解
问题三.
问题提示:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.yy.mapper.UserInfoMapper.selectByPrimaryKey
解决:在application.properties中添加生成的xml的位置
3.2运行项目
3.2.1 浏览器访问http://localhost:8888/druid/login.html,打开Druid监控页面
登录后,可查看监控界面如下
3.2.2,访问controler中的getById,http://localhost:8888/users/getById/3
index.html页面模板信息为
Title spring boot
用户信息:姓名年龄工作
查询id为3的用户信息,查询成功,返回用户信息,并在index.html中显示查询出来的用户信息。
3.2.3 查看数据库访问监控
上面执行一条查询后,在druid监控页面查看监控情况,如下:
点开上面查询语句,查看详情,
完毕!