<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
数据库驱动?
为什么导入JDBC场景,官方不导入驱动?官方不知道我们接下要操作什么数据库。
数据库版本和驱动版本对应
默认版本:<mysql.version>8.0.22</mysql.version>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.49</version>-->
</dependency>
想要修改版本
1、直接依赖引入具体版本(maven的就近依赖原则)
2、重新声明版本(maven的属性的就近优先原则)
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.49</mysql.version>
</properties>
一开始要导入jdbc启动器和mysql数据库驱动
<!--jdbc 和带版本号的mysql驱动 -->
<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>
DataSourceAutoConfiguration : 数据源的自动配置
@Configuration(proxyBeanMethods = false)
@Conditional(PooledDataSourceCondition.class)
@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
@Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
protected static class PooledDataSourceConfiguration
DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置
JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud
JndiDataSourceAutoConfiguration: jndi的自动配置
XADataSourceAutoConfiguration: 分布式事务相关的
spring:
datasource:
url: jdbc:mysql://localhost:3306/tx
username: root
password: 126433
driver-class-name: com.mysql.jdbc.Driver
jdbc:
template:
query-timeout: 1 #查询的超时时间
@SpringBootTest
class SpringBootDaoApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads()
{
Long num = jdbcTemplate.queryForObject("select count(*) from employee", Long.class);
System.out.println("查询到的记录数为: "+num);
}
}
整合第三方技术的两种方式: 自定义 找starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
<!--原生方法是给容器中放一个数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="20" />
springboot的做法: 在配置类中给容器中直接注入一个数据源
@Configuration
public class WebConfig implements WebMvcConfigurer
{
//给容器中放置一个数据源
@Bean
//将注入容器的DataSource组件的属性与配置文件中spring.datasource下面的值进行绑定
@ConfigurationProperties("spring.datasource")
public DataSource dataSource()
{
return new DruidDataSource();
}
}
需要在容器中放入一个servlet,这样才能开启监控功能
//配置Druid的监控页面功能
@Bean
public ServletRegistrationBean statViewServlet()
{
StatViewServlet statViewServlet=new StatViewServlet();
//配置该servl拦截路径
ServletRegistrationBean<StatViewServlet> serlvet = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
return serlvet;
}
只是打开了监控的页面
//给容器中放置一个数据源
@Bean
//将注入容器的DataSource组件的属性与配置文件中spring.datasource下面的值进行绑定
@ConfigurationProperties("spring.datasource")
public DataSource dataSource() throws SQLException {
DruidDataSource druidDataSource = new DruidDataSource();
//加入监控功能
druidDataSource.setFilters("stat");
return druidDataSource;
}
当我们执行一次sql语句时,就可以去查询一下这个语句执行的相关信息
//WebStatFilter用于采集web-jdbc关联监控的数据
@Bean
public FilterRegistrationBean WebStatFilter(){
WebStatFilter webStatFilter=new WebStatFilter();
FilterRegistrationBean<WebStatFilter> fb= new FilterRegistrationBean<>(webStatFilter);
fb.setUrlPatterns(Arrays.asList("/*"));
fb.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return fb;
}
//给容器中放置一个数据源
@Bean
//将注入容器的DataSource组件的属性与配置文件中spring.datasource下面的值进行绑定
@ConfigurationProperties("spring.datasource")
public DataSource dataSource() throws SQLException {
DruidDataSource druidDataSource = new DruidDataSource();
//加入监控功能, wall:开启防火墙功能
druidDataSource.setFilters("stat,wall");
return druidDataSource;
}
//配置Druid的监控页面功能
@Bean
public ServletRegistrationBean statViewServlet()
{
StatViewServlet statViewServlet=new StatViewServlet();
//配置该servl拦截路径
ServletRegistrationBean<StatViewServlet> serlvet = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
serlvet.addInitParameter("loginUsername","大忽悠");
serlvet.addInitParameter("loginPassword","123456");
return serlvet;
}
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
扩展配置项 spring.datasource.druid,在主配置文件中以这个前缀开头,就可以修改相关属性配置
DruidSpringAopConfiguration.class, 监控SpringBean的;配置项:spring.datasource.druid.aop-patterns
DruidStatViewServletConfiguration.class, 监控页的配置:spring.datasource.druid.stat-view-servlet;默认开启
DruidWebStatFilterConfiguration.class, web监控配置;spring.datasource.druid.web-stat-filter;默认开启
DruidFilterConfiguration.class}) 所有Druid自己filter的配置
private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat";
private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config";
private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding";
private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j";
private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j";
private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2";
private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log";
private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
druid:
aop-patterns: com.atguigu.admin.* #监控SpringBean
filters: stat,wall,slf4j # 底层开启功能,stat(sql监控),wall(防火墙),slf4j(日志)
stat-view-servlet: # 配置监控页功能
enabled: true
login-username: admin
login-password: admin
resetEnable: false #禁用重置按钮
web-stat-filter: # 监控web--url监控
enabled: true
urlPattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
filter:
stat: # 对上面filters里面的stat的详细配置
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
config:
drop-table-allow: false
引入starter
SpringBoot官方的Starter:spring-boot-starter-*
*第三方的: -spring-boot-starter
我们要引入的是第三方的启动器
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
全局配置文件
@EnableConfigurationProperties(MybatisProperties.class) : MyBatis配置项绑定类。
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration{}
@ConfigurationProperties(prefix = "mybatis")
public class MybatisProperties
# 配置mybatis规则
mybatis:
config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
@Mapper注解扫描Mapper接口---->Mapper接口--->绑定Xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.admin.mapper.AccountMapper">
<!-- public Account getAcct(Long id); -->
<select id="getAcct" resultType="com.atguigu.admin.bean.Account">
select * from account_tbl where id=#{id}
</select>
</mapper>
# 配置mybatis规则
mybatis:
# config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true 驼峰命名规则的开启
可以不写全局配置文件,所有全局配置文件的配置都放在configuration配置项中即可
config-location和configuration不能同时写,因为写了configuration就顶替了myBaits默认的全局配置文件
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
}
@Mapper
public interface UserMapper
{
public UserDao getUser(String name);
@Insert("INSERT INTO USER(`name`,age) VALUES(name,age)")
@Options(useGeneratedKeys = true,keyProperty = "id")//获取自增主键的值,赋值给参数上的对象
public Integer InsertUser(UserDao user );
}