目录

- spring:
- datasource:
- username: root
- password: root
- url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
- driver-class-name: com.mysql.cj.jdbc.Driver
- @SpringBootTest
- class Springboot04JdbcApplicationTests {
- @Autowired
- DataSource dataSource;//注入依赖
- @Test
- void contextLoads() throws SQLException {
- System.out.println(dataSource.getClass());//测试一下类型
- Connection connection = dataSource.getConnection();
- System.out.println(connection);
- }
- }
可以得到数据源为:class com.zaxxer.hikari.HikariDataSource
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
query方法及queryForXXX方法:用于执行查询相关语句;
call方法:用于执行存储过程、函数相关语句。
- @RestController
- public class JDBCController {
-
- @Autowired
- JdbcTemplate jdbcTemplate;
-
- @RequestMapping(value = "/list")
- public List
- String sql = "select * from user";
- List
- return list;
- }
- }
在yml中设置type
type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
- initialSize: 5
- minIdle: 5
- maxActive: 20
- maxWait: 60000
- timeBetweenEvictionRunsMillis: 60000
- minEvictableIdleTimeMillis: 300000
- validationQuery: SELECT 1 FROM DUAL
- testWhileIdle: true
- testOnBorrow: false
- testOnReturn: false
- poolPreparedStatements: true
- @Configuration
- public class DruidConfig {
-
- @ConfigurationProperties(prefix = "spring.datasource")
- @Bean
- public DataSource druidDataSource(){
- return new DruidDataSource();
- }
- }
@ConfigurationProperties(prefix = "spring.datasource"):
将全局配置文件中前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
- @Bean
- public ServletRegistrationBean servletRegistrationBean(){
- ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
- HashMap
init = new HashMap<>(); - init.put("loginUsername","admin");//初始化
- init.put("loginPassword","123");
- //后台允许谁访问
- init.put("allow","");
-
- bean.setInitParameters(init);
- return bean;
- }
当执行一次sql时,后台会有监视

- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>2.1.1version>
- dependency>
- @Mapper
- @Component
- public interface UserMapper {
- List
query(); - }
@Mapper : 表示本类是一个 MyBatis 的 Mapper
使用Lombok注解
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class User {
- int id;
- String name;
- String password;
- }
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.demos.mapper.UserMapper">
- <select id="query" resultType="User">
- select * from user
- select>
- mapper>
- @RestController
- public class UserController {
-
- @Autowired
- UserMapper userMapper;
-
- @RequestMapping(value = "/query")
- public List query(){
- List
query = userMapper.query(); - return query;
- }
- }