一、Springboot连接数据的方式主要有以下三种
- JDBC
- Mybatis
- Spring Data JPA
二、springboot整合JDBC
1.创建项目,引入stater
查看pom.xml,主要依赖已经引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.编写yml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/test2
driver-class-name: com.mysql.jdbc.Driver
3.修改测试类进行测试
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
Connection connection = dataSource.getConnection();
System.out.println("connection:" + connection);
connection.close();
}
}
输出:
connection:HikariProxyConnection@1054913783 wrapping com.mysql.cj.jdbc.ConnectionImpl@79b84841
springboot 默认可以支持Dbcp2,Hikari,Tomcat(springboot 2.2.5)等数据源
相关配置在DataSourceConfiguration类中
4.使用JdbcTemplate操作数据库
创建Controller
代码如下:
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/score")
public Map<String, Object> getScore() {
List<Map<String, Object>> scoreList = jdbcTemplate.queryForList("SELECT * FROM score");
return scoreList.get(0);
}
}
数据库表数据:
查询结果如下:
5.如何修改数据源
性能方面 hikari>druid>tomcat-jdbc>dbcp>c3p0 。hikari的高性能得益于最大限度的避免锁竞争。druid功能最为全面,sql拦截等功能,统计数据较为全面,具有良好的扩展性。
上面的开发中可以看到我们使用的数据源为hikari,接下来我们要将其修改为durid
(1)首先加入如下依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
(2)修改pom文件,加入type: com.alibaba.druid.pool.DruidDataSource
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/test2
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
(3)测试类进行测试
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
}
}
输出:
class com.alibaba.druid.pool.DruidDataSource
(4)更全面的连接池配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/test2
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 1 #初始化大小
minIdle: 1 #最小等待连接数量
# maxIdle: 5 最大等待连接数量,已经被弃用,报错:maxIdle is deprecated
maxActive: 20 #最大连接数
maxWait: 60000 #配置获取连接等待超时的时间
timeBetweenEvictionRunsMillis: 60000 #间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最小生存的时间,单位是毫秒
# Oracle必须这样配置检查,不了会报检查错误
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
druid:
allow: #允许登陆的IP地址
ip: 127.0.0.1
login: #登陆的账户密码
userName: admin
password: admin123
为了使上面连接池配置生效,需要添加duridConfig配置文件
@Configuration
public class DuridConfig {
@Value("${druid.login.userName}")
private String userName;
@Value("${druid.login.password}")
private String password;
@Value("${druid.allow.ip}")
private String allowIp;
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
//配置durid的监控
//1.配置一个管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", userName); // 用户名
initParameters.put("loginPassword", password); // 密码
initParameters.put("resetEnable", "false"); // 禁用HTML页面上的“Reset All”功能
initParameters.put("allow", allowIp); // IP白名单 (没有配置或者为空,则允许所有访问)
//initParameters.put("deny", "");// IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
}
//2.注册一个web监控的filter
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
浏览器访问:http://127.0.0.1:8080/druid
重新执行请求localhost:8080/hello/score,然后查看监控记录:
网友评论