JDBC、MyBatis、Spring Data JPA
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://39.101.192.239:3389/jdbc
driver-class-name: com.mysql.cj.jdbc.Driver
效果:
默认使用class com.zaxxer.hikari.HikariDataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
自动配置原理:
1、参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;
2、SpringBoot默认可以支持;
org.apache.tomcat.jdbc.pool.DataSource
com.zaxxer.hikari.HikariDataSource
org.apache.commons.dbcp2.BasicDataSource
3、自定义数据源类型
/**
* Generic DataSource configuration.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
DataSource dataSource(DataSourceProperties properties) {
// 使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
4、DataSourceInitializerInvoker:ApplicationListener;
作用:(执行sql)
1、initialize(initializer):运行建表语句
2、initializer.initSchema():运行插入数据的sql语句
默认只需要将文件命名为:
schema-*.sql(建表的)、data-*.sql(数据的)
默认规则:schema.sql,schema-all.sql;
可以使用
schema:
- classpath:department.sql
指定位置
// 2.x版本需要注册这个,才能执行schema
spring.datasource.initialization-mode=always
5、操作数据库:自动配置了jdbcTemplate操作数据库
- 使用这个jdbcTemplate可以执行sql(也就是一些额外的)
2、整合Druid数据源
<!--导入log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--引入druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
# 前提导入数据源
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://39.101.x.x:3389/jdbc
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:sql/department.sql
# initialization-mode: always
注意在这儿要将这个log4j导入,不然后面会出问题
// 整合Druid数据源
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
// 配置一个Druid的监控
// 1、配置一个监管后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean<StatViewServlet> 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", "192.168.1.21");
bean.setInitParameters(initParams);
return bean;
}
// 2、配置一个监控的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;
}
}
3、整合MyBatis
<!--2.3.4boot版本整合-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
步骤:
1、配置数据源相关属性
spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://39.101.192.239:3389/mybatis
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
/**
* @author cai-xiansheng
* @Description
* @create 2020-10-24 20:53
*/
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druid() {
return new DruidDataSource();
}
// 配置一个Druid监控
// 1、配置一个监管后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean<StatViewServlet> 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", "192.168.1.21"); // 不允许访问的机器
bean.setInitParameters(initParams);
return bean;
}
// 2、配置一个监控的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;
}
}
2、给数据库创建表
spring:
datasource:
# 自动运行建表语句{ schema-*.sql(建表的)、data-*.sql(数据的) }
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
# 2.x版本需要注册这个,才能执行schema
initialization-mode: always
3、创建javaBean
4、注解版
// 指定这是一个操作数据库的mapper
// @Componet加上之后就不会再使用@AutoWired的时候出现爆红
@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(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);
}
};
}
}
批量扫描所有的mapper接口(使用Mapper);
也可以使用在MyBatis的config类中
@MapperScan(value = "com.zh.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文件的位置
- 在我们使用了config-location之后,我们之前的mybatisConfig文件就会失效。
- 可能是因为,mybatisAutoConfiguration的默认
更多实用参照:
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;
@Conlumn(name = "last_name", length = 50) // 这是和数据表内对应的一个列
private String lastName;
@Column // 省略列名就是属性名
private String email;
// getter and setter
}
2、编写一个Dao接口来操作实体类对应的数据表(Repository)
// 集成JpaResponsitory来完成对数据库的操作
public interface UserRepository extends JpaResponsitory<User, Integer> {
}
3、基本的配置JpaProperties
spring:
jpa:
hibernate:
# 更新或者数据表的结构
ddl-auto: update
# 控制台显示SQL
show-sql: true