1.整合JDBC和基本数据源
1)前提要导入依赖
2)application.xml配置文件
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/jpa
#默认使用数据源为Tomcat的数据源org.mysql.tomcat.jdbc.pool.DataSource
数据源的相关配置都在DataSourceProperties里面
自动配置原理DataSourceConfiguration包含配置
3)自动建表
以这种方式命名的sql文件会通过DataSourceInitailzer自动建表
schema-*.sql,data-*.sql
自定义建表的sql文件名称
spring:
datasource:
schema:
-classpath:depa.sql
-classpath:depa2.sql
#可以指定多个sql文件
4)自动配置了JdbcTemplate操作数据库
public classHelloController{
@AutoWired
JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping("/query")
public Map<String, Object> map(){
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
return list.get(0);
}
}
2.配置Bruid数据源
1)application.yml
DataSourceProperties中没有initialSize以及后面的配置,所以要创建一个配置类
2)DruidConfig.java
@Configuration
public class DruidConfig{
@ConfigurationProperties(prefix = "spring.datasource")
//将以spring.datasource为前缀的所有属性绑定进来
@Bean
//将该配置类加载到容器中
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1.配置一个管理后台的servlet
//2.配置一个监控的filter
}
目前使用默认数据源
3.整合Mybatis
1)引入依赖
2)注解模式
@mapper(mapper映射文件上的注释)或者@mapperScann(springboot运行类上的注释)
通过mapper映射接口自行编写sql
直接将sql语句写在对应的方法上
可以将mapper文件中的@mapper省略掉,在执行类里面添加注解
@MapperScan(Value = "com.hello.mapper") 自动扫描指定包中的mapper映射类
@Options(userGeneratedKeys = true, keyProperty = "id") 表示将插入的数据设置自增主键
通过@org.springframework.context.annotation.Configuration指定配置文件
通过配置类开启驼峰命名法
MybatisConfig.java
//表示这是一个配置类
@org.springframework.context.annotation.Configuration
public class MybatisConfig{
//ConfigurationCustomizer 该类可以自己指制定配置
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration){
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
3)配置文件模式
通过配置文件指定mybatis配置文件位置以及映射文件位置
application.yml
mybatis:
config-location: classpath:mybatis-config.xml 指定全局配置文件位置
mapper-location: classpath: classpath:mybatis/mapper/*.xml 指定映射文件的位置
通过xml配置文件开启驼峰命名法
mybatis-config.xml
<configuration>
<settings>
<setting name = "mapUnderscoreToCamelCase" value = "true">
<settings>
<configuration>
4.遗留问题
通过配置类来对mybatis配置进行设置,程序如何识别该配置类就是mybatis的配置
通过mapper来编写sql语句时,如何进行动态sql的编写
//todo
5.注意问题
application.xml配置文件
username: root
username后面有空格。