简介:
对于数据访问,无论是SQL(关系型的数据库)还是NOSQL(非关系型的数据库),SpringBoot默认采用整合Spring Data的方式进行统一的处理。添加大量的自动配置,屏蔽一些配置,引入各种XXXTemplate,XXXRepository来简化我们对数据访问的操作。
JDBC:
在pom.xml中添加JDBC和mysql的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
// 下面这行去除,否则在application.yml中编写JDBC配置时, driverClassName会提示红色
<scope>runtime</scope>
</dependency>
在application.yml 中添加JDBC的配置:
//默认提示版本:运行测试会报错
spring:
datasource:
data-username: root
data-password: root
url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
报错提示: 由于用户名,密码属性名称不对,导致报错;
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
解决方法:
//修改用户名和密码属性名称
spring:
datasource:
username: root
password: root
//Mysql JDBC 6.0版本以上需要配置时区serverTimezone=UTC ,否则会报错
url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
说明:
SpringBoot1.5.x 版本: 默认是用 org.apache.tomcat.jdbc.pool.DataSource作为数据源;
SpringBoot2.x.x 版本: 默认是用 com.zaxxer.hikari.HikariDataSource作为数据源;
数据源的相关配置: 都在DataSourceProperties类中;
自动配置原理: org.springframework.boot.autoconfigure.jdbc;
DataSourceConfiguration: 根据配置创建数据源,可以使用 spring.datasource.type 指定自定义的数据源类型;
SpringBoot 默认支持:
org.apache.commons.dbcp2.BasicDataSource
com.zaxxer.hikari.HikariDataSource
org.apache.tomcat.jdbc.pool.DataSource
自定义数据源类型:
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(name = {"spring.datasource.type"})
static class Generic {
Generic() {
}
@Bean
DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
整合Druid数据源:
在 pom.xml 中添加 druid数据源 依赖:
<!--引入druid数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
在 application.yml 中指定druid数据源 :
type: com.alibaba.druid.pool.DruidDataSource
//配置druid数据源 属性
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
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
自定义配置类: 用于配置druid数据源,并注册到容器中;
//导入druid数据源
@Configuration
public class DruidConfig {
//绑定application.yml文件中spring.datasource的所有属性
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","127.0.0.1");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
整合MyBatis:
在 pom.xml 中添加 MyBatis 的依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
注解版本:
编写Mapper接口文件:
@Mapper //指定这是操作数据库的mapper
@Component
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(department_name) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
注意点: 当表结构字段和Java文件中表结构字段不一致时,自定义配置类,开启驼峰命名规则;
自定义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);
}
};
}
}
注意点: 当存在多个Mapper时,给每个Mapper接口添加 @Mapper 注解很麻烦;可以在SpringBoot主配置上添加 @MapperScan注解并指定路径,这样该路径下所有Mapper接口自动添加 @Mapper 注解;
@MapperScan(value = "com.yp.spring_boot.mapper") //使用 @MapperScan 批量扫描
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
配置文件版本:
直接在 application.yml 中指定全局配置文件和sql映射文件:
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
全局配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
//开启驼峰命名规则
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
sql映射文件:
<?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.yp.spring_boot.mapper.EmployeeMapper"> <!--指定namespace-->
<!--查询-->
<select id="getEmpById" resultType="com.yp.spring_boot.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<!-- 新增-->
<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
SpringData :
简介:
SpringData项目的目的是为了简化构建基于Spring框架应用的数据访问技术,包括非关系型数据库、Map-Reduce框架、云数据服务等等;它也包含对关系型数据库的访问支持;
特点:
提供统一的API来对数据访问层进行操作 | 主要是Spring Data Commons项目实现,它让我们在使用关系型数据访问或者非关系型数据访问时都基于Spring提供的统一标准,包括CRUD(创建、获取、更新、删除)、查询、排序、分页等相关操作; |
统一的Repository接口 | Repository<T,ID extends Serializable>: 统一接口; RevisionRepository<T,ID extends Serializable,N extends Number & Comparable< N >>: 基于乐观锁机制; CrudRepository<T,ID extends Serializable>: 基本CRUD操作; PagingAndSortingRepository<T,ID extends Serializable>: 基本分页; |
提供数据访问模板类 xxxTemlate |
JPA 与 Spring Data:
JpaRepository基本功能 | 编写接口继承JpaRepository已有的crud和分页等基本功能; |
定义符合规范的方法命名 | 在接口中只需要声明符合规范的方法就可以拥有对应的功能; |
@Query自定义查询 | 定制查询SQL; |
Specifications查询 |
整合SpringData JPA:
编写实体类(bean)和数据表进行映射,并且配置好映射关系:
@Entity //使用@Entity注解告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table注解来指定和哪个数据表对应,如果省略默认表名就是user
public class User {
@Id //使用@Id注解表明这是主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//使用@GeneratedValue注解表明自增主键
private Integer id;
@Column(name = "last_name",length = 50) //使用@Column注解表明这是和数据表对应的列,列名为last_name
private String lastName;
@Column //省略默认列名就是属性名
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
编写Dao接口来操作实体类对应的数据表:
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}
在application.yml中进行数据连接配置和jpa配置:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
# 更新或者创建数据表结构
ddl-auto: update
# 控制台显示SQL
show-sql: true