spring-boot-SpringBoot與資料訪問
1.JDBC
(1).匯入依賴
<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).application.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.22:3306/jdbc
效果:
預設是org.apache.tomcat.jdbc.pool.DataSource作為資料來源
資料來源的相關配置都在DataSourceProperties裡面
3).自動配置原理:
在org.springframework.boot.autoconfigure.jdbc檢視
1.參考DataSourceConfiguration,根據配置建立資料來源,預設使用Tomcat連線池;可以使用spring.datasource.type指定自定義的資料型別;
@ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class) @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true) static class Tomcat extends DataSourceConfiguration { @Bean @ConfigurationProperties(prefix = "spring.datasource.tomcat")
2.SpringBoot預設可以支援
org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource
3.自定義資料型別(檢視原始碼)
/**
* Generic DataSource configuration.
*/
@ConditionalOnMissingBean(DataSource.class) @ConditionalOnProperty(name="spring.datasource.type") staticclassGeneric{
@Bean
public DataSource dataSource(DataSourceProperties properties) { //使用DataSourceBuilder建立資料來源,利用反射建立響應type的資料來源,並且繫結相關屬性
return properties.initializeDataSourceBuilder().build();
}
}
4)DataSourceInitializer:ApplicationListener;
作用:
a.run SchemaScripts();執行建表語句
b.run SchemaScripts();執行插入資料的sql語句;
預設只需要將檔案命名為:
schema-*.sql、 data-*.sql
預設規則:schema.sql,schema-all.sql
可以使用
schema:
- classpath:department.sql
指定位置
2.整合Druid資料來源
(1)匯入依賴
<!--引入druid資料來源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
2)applicaton.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.22:3306/jdbc
driver-class-name: com.mysql.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:department.sql
3).匯入資料來源
//讀取配置檔案中Druid的值
@Configuration
public class DruidConfig {
@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","192.168.15.21");
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;
}
}
3.整合mybatis
(1)匯入依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis‐spring‐boot‐starter</artifactId>
<version>1.3.1</version>
</dependency
步驟:
a.配置資料來源相關屬性(見上一節)
b.給資料庫建表
c.建立javaBean(此處不添程式碼了)
(2)註解版
//指定這是一個操作資料庫的mapper 2 @Mapper
publicinterfaceDepartmentMapper{
@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(開啟駝峰命名 例如 資料庫欄位是last_name javaBean
可以是lastName)
@org.springframework.context.annotation.Configuration publicclass
MyBatisConfig{
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
springbootApplication
package com.atguigu.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
使用MapperScan掃描所有的mapper介面,可以省去每個mapper介面加@Mapper
@MapperScan(value="com.hbsi.mapper")
@SpringBootApplication
public class SpringBoot06DataJdbcApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataJdbcApplication.class, args);
}
}
(3)配置檔案版(此處不做詳解,只標明如何掃描配置檔案)
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/