在pom.xml里添加jar包:
org.springframework.boot
spring-boot-starter-jdbc
com.alibaba
druid
1.0.26
org.mybatis
mybatis-spring
1.2.2
org.mybatis
mybatis
3.2.8
mysql
mysql-connector-java
5.0.5
1、在application.properties里添加
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
2、在resources里创建mybatis.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db
spring.datasource.username=root
spring.datasource.password=123456
# 初始化大小,最小,最大
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,logback
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3、在com.demo下创建文件夹mybatis,创建文件MybatisConfig
- package com.query.mybatis;
-
- import lombok.extern.slf4j.Slf4j;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.mybatis.spring.SqlSessionFactoryBean;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.Primary;
- import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
- import javax.sql.DataSource;
-
-
-
-
- @Configuration
- @Slf4j
- @EnableTransactionManagement
- @ComponentScan
- @MapperScan("com.demo.mapper")
- public class MybatisConfig {
- @Value("${spring.datasource.type}")
- private Class extends DataSource> dataSourceType;
-
- @Bean(name="dataSource", destroyMethod = "close", initMethod="init")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- log.info("-------------------- writeDataSource init ---------------------");
- return DataSourceBuilder.create().type(dataSourceType).build();
- }
- @Bean
- public SqlSessionFactory sqlSessionFactory() throws Exception {
- SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
- sqlSessionFactoryBean.setDataSource(dataSource());
- sqlSessionFactoryBean.setTypeAliasesPackage("com.demo.model");
- PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
- sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/demo/mapper/*.xml"));
- sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
- return sqlSessionFactoryBean.getObject();
- }
- /**
- * 配置事务管理器
- */
- @Bean(name = "transactionManager")
- @Primary
- public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) throws Exception {
- return new DataSourceTransactionManager(dataSource);
- }
- }
以上就完成了配置,测试,在com/demo下创建mapper文件夹,创建UserMapper
- package com.demo.mapper;
-
-
- import com.demo.model.User;
- import org.apache.ibatis.annotations.ResultType;
- import org.apache.ibatis.annotations.Select;
- import org.springframework.stereotype.Repository;
-
-
-
-
-
- @Repository("userMapper")
- public interface UserMapper {
- @Select("SELECT * from `user` where user_code = #{userCode}")
- @ResultType(User.class)
- User selectByPrimaryKey(Integer userCode);
- }
如果使用mapper.xml,要在pom.xml里添加
否则mapper编译不到target里。
在com/demo下创建model文件夹,创建User
- package com.demo.model;
-
-
- import lombok.Data;
-
-
-
-
-
- @Data
- public class User {
- private Integer userCode;
- private String mobileNumber;
- }
在com/demo下创建service文件夹,创建service文件,接口类忽略了,只复制实现类
- package com.demo.service.impl;
-
-
- import com.demo.mapper.UserMapper;
- import com.demo.model.User;
- import com.demo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
-
-
-
-
- @Service("userService")
- public class UserServiceImpl implements UserService {
- @Autowired
- private UserMapper userMapper;
- @Override
- public User selectByPrimaryKey(Integer userCode) {
- return userMapper.selectByPrimaryKey(userCode);
- }
- }
可以查询到数据。
4、用druid监控数据库,在com/demo下创建文件夹druid,创建文件DruidDataSourceConfig
- package com.demo.druid;
-
-
- import org.springframework.boot.bind.RelaxedPropertyResolver;
- import org.springframework.context.EnvironmentAware;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.env.Environment;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-
-
-
-
-
- @Configuration
- @EnableTransactionManagement
- public class DruidDataSourceConfig implements EnvironmentAware {
- private RelaxedPropertyResolver propertyResolver;
-
-
- public void setEnvironment(Environment env) {
- this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
- }
- }
创建DruidStatFilter
- package com.demo.druid;
-
-
- import com.alibaba.druid.support.http.WebStatFilter;
-
-
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.annotation.WebInitParam;
-
-
-
-
-
-
- @WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
- initParams={
- @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")
- })
- public class DruidStatFilter extends WebStatFilter {
- }
创建DruidStatViewServlet
- package com.demo.druid;
-
-
- import com.alibaba.druid.support.http.StatViewServlet;
-
-
- import javax.servlet.annotation.WebInitParam;
- import javax.servlet.annotation.WebServlet;
-
-
-
-
-
-
- @SuppressWarnings("serial")
- @WebServlet(urlPatterns = "/druid/*",
- initParams={
- @WebInitParam(name="allow",value="127.0.0.1,192.168.1.126"),
- @WebInitParam(name="deny",value="192.168.1.111"),
- @WebInitParam(name="loginUsername",value="root"),
- @WebInitParam(name="loginPassword",value="123456"),
- @WebInitParam(name="resetEnable",value="false")
- })
- public class DruidStatViewServlet extends StatViewServlet {
- }
在DemoApplication上面添加@ServletComponentScan
创建好之后,我们访问 http://localhost/druid/index.html,会自动跳到http://localhost/druid/login.html登录页面
账户和密码为上面的