目录
- JDBC
- 整合Druid数据源
一、JDBC
1.导入SpringBoot jdbc依赖
<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配置文件中配置jdbc

3.效果
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源; 数据源的相关配置都在DataSourceProperties里面;
4.自动配置原理
org.springframework.boot.autoconfigure.jdbc:
- 参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用 spring.datasource.type指定自定义的数据源类型;
- SpringBoot默认可以支持:org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource等等数据源;还可以自定义数据源类型,例如:
/** * Generic DataSource configuration. */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name="spring.datasource.type")
static class Generic{
@Bean
public DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build(); }
}
5.DataSourceInitializer:ApplicationListener;
作用: runSchemaScripts();运行建表语句;
runDataScripts();运行插入数据的sql语句;
默认只需要将文件命名为:
schema‐*.sql、data‐*.sql
默认规则:schema.sql,schema‐all.sql;
可以使用
schema:
‐ classpath:department.sql
指定位置
6. 操作数据库: 操作数据库:自动配置了JdbcTemplate操作数据库
二、整合Druid数据源


三、整合Mybatis
1.导入mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis‐spring‐boot‐starter</artifactId>
<version>1.3.1</version>
</dependency>

2. 步骤
①配置数据源相关属性(见上一节Druid) 2)
②给数据库建表
③创建JavaBean
④操作:
- 注解版
//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper{ 4
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
//用来指定开启自增主键
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
问题:数据库中数据是以depart_name的形式进行字段命名的,需要开启驼峰规则,没有了mybatis文件怎么开启驼峰规则?
@org.springframework.context.annotation.Configuration publicclassMyBatisConfig{
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
} };
} }

- 配置文件版
其他的操作方法都和原来的差不多,主要是在yml文件中绑定mybatis的配置文件和mapper的xml文件
mybatis:
config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
mapper‐locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
四、整合JPA
- JPA简介

2. 整合JPA
- 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;

- 编写一个Dao接口来操作实体类对应的数据表(Repository)

- 基本的配置JpaProperties
