對於數據訪問層,無論是SQL還是NOSQL,SpringBoot底層都是采用SpringData的方式進行處理
集成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 data-password: 13476110270dwx url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
測試
@Test void testData() throws SQLException { //查看數據源類型 System.out.println(dataSource.getClass()); //獲取連接 Connection connection=dataSource.getConnection(); System.out.println(connection); //關閉連接 connection.close(); }
默認的數據源是class com.zaxxer.hikari.HikariDataSource,是當前速度最快的數據源
可以使用spring.datasource.type指定數據源類型
JdbcTemplate
有了數據源就可以拿到數據庫連接,拿到了連接就可以使用原生的JDBC語句來操作數據庫
Spring本身對原生的JDBC進行了封裝,JdbcTemplate
數據庫所有的CRUD方法都在JdbcTemplate中
SpringBoot也提供配置好的JdbcTemplate放在容器中,只需注入就好,JdbcTemplate會自己注入數據源簡化操作
JdbcTemplate主要提供以下幾類方法:
- execute():可以執行crud語句
- update()與batchUpdate():執行和批量執行cud語句
- query()與queryForXXX():執行相關查詢語句
- call():執行存儲過程,函數先相關語句
@RestController @RequestMapping("/test") public class JdbcController { @Autowired JdbcTemplate jdbcTemplate; @GetMapping("/query") public List<Map<String,Object>> userList(){ String sql="select * from employee"; List<Map<String,Object>> maps=jdbcTemplate.queryForList(sql); return maps; } @GetMapping("/delete/{id}") public String delUser(@PathVariable("id") int id){ String sql = "delete from employee where id=?"; jdbcTemplate.update(sql,id); return "deleteOk"; } }
集成Druid
Druid是一個數據庫連接池的實現,結合了DBCP和C3P0的優點,並加入了日志監控
將數據源切換到Druid
導入依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency>
切換數據源,並配置Druid的屬性(這些屬性SpringBoot不會注入,需要手動綁定)
spring:
datasource:
username: root
data-password: 13476110270dwx
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默認是不注入這些屬性值的,需要自己綁定
#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:監控統計、log4j:日志記錄、wall:防御sql注入
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
手動綁定屬性
@Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } }
測試
@Autowired DataSource dataSource; @Test void testData() throws SQLException { //查看數據源類型 System.out.println(dataSource.getClass()); //獲取連接 Connection connection=dataSource.getConnection(); System.out.println(connection); DruidDataSource druidDataSource=(DruidDataSource) dataSource; System.out.println(druidDataSource.getMaxActive()); System.out.println(druidDataSource.getInitialSize()); //關閉連接 connection.close(); }
Durid數據源監控
Druid提供一個Web界面方便查看
配置后台管理
//配置 Druid 監控管理后台的Servlet; //內置 Servlet 容器時沒有web.xml文件,所以使用 Spring Boot 的注冊 Servlet 方式 @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 這些參數可以在 com.alibaba.druid.support.http.StatViewServlet // 的父類 com.alibaba.druid.support.http.ResourceServlet 中找到 Map<String, String> initParams = new HashMap<>(); initParams.put("loginUsername", "admin"); //后台管理界面的登錄賬號 initParams.put("loginPassword", "123456"); //后台管理界面的登錄密碼 //后台允許誰可以訪問 //initParams.put("allow", "localhost"):表示只有本機可以訪問 //initParams.put("allow", ""):為空或者為null時,表示允許所有訪問 initParams.put("allow", ""); //deny:Druid 后台拒絕誰訪問 //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip訪問 //設置初始化參數 bean.setInitParameters(initParams); return bean; }
登錄:localhost:8080/druib/login.html
配置監控過濾器
//WebStatFilter:用於配置Web和Druid數據源之間的管理關聯監控統計 @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); //exclusions:設置哪些請求進行過濾排除掉,從而不進行統計 Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*"); bean.setInitParameters(initParams); //"/*" 表示過濾所有請求 bean.setUrlPatterns(Arrays.asList("/*")); return bean; }
Mybatis整合
導入mybatis依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
創建實體類
@Data @AllArgsConstructor @NoArgsConstructor public class Department { private int id; private String departmentName; }
創建mapper接口
@Mapper @Repository public interface DepartmentMapper { //得到全部部門 List<Department> getDepartments(); //通過id獲得部門 Department getDepartmentById(int id); }
創建對應的mapper.xml文件
<mapper namespace="com.deng.test.dao.DepartmentMapper"> <select id="getDepartments" resultType="com.deng.test.pojo.Department"> select * from department; </select> <select id="getDepartmentById" resultType="com.deng.test.pojo.Department"> select * from department where id=#{id}; </select> </mapper>
告訴SpringBoot mapper.xml文件的位置
mybatis:
mapper-locations: com/deng/test/dao/*.xml
測試
@RestController public class DepartmentController { @Autowired DepartmentMapper departmentMapper; // 查詢全部部門 @GetMapping("/getDepartments") public List<Department> getDepartments(){ return departmentMapper.getDepartments(); } // 查詢全部部門 @GetMapping("/getDepartment/{id}") public Department getDepartmentById(@PathVariable("id") int id){ return departmentMapper.getDepartmentById(id); } }