SpringBoot与数据访问
1、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>
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.22:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
效果:
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
自动配置原理:
org.springframework.boot.autoconfigure.jdbc:
1、参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;
2、SpringBoot默认可以支持;
org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource、
3、自定义数据源类型
/**
* 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();
}
}
2、整合Druid数据源
- 导入Druid连接池的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.4</version>
</dependency>
- 更改springboot对于连接池的默认配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: 123456
#当前版本的druid数据池是我们自己导入的,并不是springboot的启动器
#springboot默认是不注入以下属性值的,这些属于Druid数据池的私有属性
initialSize: 5
minIdle: 5
maxActive: 20
#配置 filter:监控统计拦截、stat:监控统计、log4j:日志记录、wall:防御sql注入
#若报错:org.apache.log4j.Priority,则导入log4j的依赖即可
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.merSql=true;druid.stat.slowSqlMillis=500
- 在spring容器中添加Druid连接池,并配置连接池属性
/*
1. 因为在application.yml文件中,已经设置了Druid连接池的私有属性
2. 直接绑定到该容器上即可,无需再手动配置
3. */
@Bean
@ConfigurationProperties("spring.datasource")
public DruidDataSource getDruidDataSource() {
return new DruidDataSource();
}
Druid连接池自带后台监控页面
- 需要在容器中添加Druid连接池时,给该连接池设置一些属性
spring:
datasource:
#当前版本的druid数据池是我们自己导入的,并不是springboot的启动器
#springboot默认是不注入以下属性值的,这些属于Druid数据池的私有属性
initialSize: 5
minIdle: 5
maxActive: 20
#配置 filter:监控统计拦截、stat:监控统计、log4j:日志记录、wall:防御sql注入
#若报错:org.apache.log4j.Priority,则导入log4j的依赖即可
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.merSql=true;druid.stat.slowSqlMillis=500
- 注册一个Servlet(Druid连接池提供的)
/*
* druid连接池自带一个后台监控页面
* ServletRegistrationBean:相当于一个 web.xml,在里面配置了一个servlet
* SpringBoot 内置了 Servlet容器,所以没有web.xml,替代方法:xxxRegistrationBean
* */
@Bean
public ServletRegistrationBean statViewServlet() {
//固定写法(配置了一个Druid提供的Servlet,映射/druid...请求)
ServletRegistrationBean<StatViewServlet> bean
= new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
/*
* 后台需要有人登录,需要设置账户密码
* 其中参数名称是固定的
* */
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "maki"); //设置用户名
initParameters.put("loginPassword", "123"); //设置密码
//设置该后台页面谁可以访问(现在是只允许本机访问)
initParameters.put("allow", "localhost");
//禁止谁能访问 initParameters.put("maki","127.0.0.1");
bean.setInitParameters(initParameters); //设置初始化参数
return bean;
}
SpringBoot中注册原生Servlet组件
通过xxxRegistrationBean的方式
例如:注册一个Filter过滤器(阿里巴巴提供的)
/*
1. Filter过滤器
2. 相当于在 web.xml中,配置了一个Filter
3. */
@Bean
public FilterRegistrationBean webStatFilter(){
//相当于在web.xml中,配置了一个过滤器WebStatFilter(该过滤器是阿里巴巴提供的)
FilterRegistrationBean bean=new FilterRegistrationBean(new WebStatFilter());
//设置哪些东西不拦截(exclusions,可以通过WebStatFilter该过滤器的源码中得知)
HashMap<String, String> initParameters = new HashMap<String, String>();
initParameters.put("exclusions","*.js,*.css,/druid/*");
//给该过滤器添加一些属性
bean.setInitParameters(initParameters);
return bean;
}
3、整合MyBatis
步骤:
1)、配置数据源相关属性(见上一节Druid)
2)、导入整合依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
4)、注解版
//该注解相当于一个sql映射文件(xxx.xml)、会自动生成代理对象,存入容器
@Mapper
@Repository
public interface DepartmentMapper {
@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);
}
问题:
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
//开启驼峰命名
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
//使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
5)、配置文件版
mybatis:
config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
更多使用参照
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
4、整合SpringData JPA
1)、SpringData简介
2)、整合SpringData JPA
JPA:ORM(Object Relational Mapping);
1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {
@Id //这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
private Integer id;
@Column(name = "last_name",length = 50) //这是和数据表对应的一个列
private String lastName;
@Column //省略默认列名就是属性名
private String email;
2)、编写一个Dao接口来操作实体类对应的数据表(Repository)
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}
3)、基本的配置JpaProperties
spring:
jpa:
hibernate:
# 更新或者创建数据表结构
ddl-auto: update
# 控制台显示SQL
show-sql: true