日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Spring Boot数据库操作原理及整合druid数据源和mybatis

發(fā)布時(shí)間:2025/4/16 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot数据库操作原理及整合druid数据源和mybatis 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

在Spring Boot中如果需要訪問(wèn)數(shù)據(jù)庫(kù),我需要導(dǎo)入以下兩個(gè)依賴:

<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>

之后在配置文件中配置好數(shù)據(jù)庫(kù):

spring:datasource:username: rootpassword: 123456url: jdbc:mysql://192.168.15.22:3306/jdbcdriver‐class‐name: com.mysql.jdbc.Driver

之后直接使用JdbcTemplate來(lái)操作數(shù)據(jù)庫(kù)即可,默認(rèn)是用org.apache.tomcat.jdbc.pool.DataSource作為數(shù)據(jù)源。那么這些是如何完成的呢?可以接著往下看。注意:我使用的是Spring Boot 2.1.7版本,不同版本可能源碼有不同。

在Spring Boot的autoconfigure包下有一個(gè)叫jdbc的包,其中幫我們做好了數(shù)據(jù)庫(kù)的配置,可以查看DataSourceConfiguration,根據(jù)配置創(chuàng)建數(shù)據(jù)源,默認(rèn)使用Tomcat連接池;可以使用spring.datasource.type指定自定義的數(shù)據(jù)源類型,如果沒(méi)有指定的話,就使用org.apache.tomcat.jdbc.pool.DataSource數(shù)據(jù)源了,默認(rèn)支持org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource這些數(shù)據(jù)源。在該文件的最后還有這么一段:

/*** Generic DataSource configuration.*/@Configuration@ConditionalOnMissingBean(DataSource.class)@ConditionalOnProperty(name = "spring.datasource.type")static class Generic {@Beanpublic DataSource dataSource(DataSourceProperties properties) {return properties.initializeDataSourceBuilder().build();}}

它的意思是,如果我們配置的spring.datasource.type不是上面任意一個(gè)數(shù)據(jù)源,就使用這種方式創(chuàng)建數(shù)據(jù)源,其原理是使用DataSourceBuilder創(chuàng)建數(shù)據(jù)源,利用反射創(chuàng)建type指定的數(shù)據(jù)源,并且綁定相關(guān)屬性。此外,Spring Boot還可以幫我自動(dòng)運(yùn)行建表和數(shù)據(jù)創(chuàng)建.sql腳本。這又是如何實(shí)現(xiàn)的呢?接著往下看。

在jdbc包下還有一個(gè)DataSourceInitializerInvoker類,它繼承了ApplicationListener,所以它是一個(gè)監(jiān)聽(tīng)器,監(jiān)聽(tīng)什么呢?這個(gè)類的注釋中給出了解釋:

/*** Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on* {@link InitializingBean#afterPropertiesSet()} and {@literal data-*.sql} SQL scripts on* a {@link DataSourceSchemaCreatedEvent}.** @author Stephane Nicoll* @see DataSourceAutoConfiguration*/

也就是說(shuō),如果InitializingBean#afterPropertiesSet()發(fā)生時(shí)運(yùn)行schema-.sql腳本,發(fā)生DataSourceSchemaCreatedEvent時(shí)運(yùn)行data-.sql 腳本。所以如果當(dāng)你需要在程序運(yùn)行的時(shí)候建表,直接在classpate下創(chuàng)建schema-.sql建表文件即可。如果你還需要插入數(shù)據(jù),直接在classpate下創(chuàng)建data-.sql插入數(shù)據(jù)文件即可。不過(guò)Spring Boot也支持你直接在數(shù)據(jù)庫(kù)中聲明schema文件的位置和名稱,如:

Spring:datasource:schema:‐ classpath:department.sql

最后需要注意的是,如果你在classpate下創(chuàng)建了schema-*.sql建表文件,那么每次啟動(dòng)程序都會(huì)運(yùn)行這個(gè)腳本,所以當(dāng)你不需要建表的時(shí)候,注意要及時(shí)刪除。

最后,在JdbcTemplateAutoConfiguration文件還自動(dòng)幫我創(chuàng)建好了JdbcTemplate,使用的時(shí)候直接自動(dòng)注入即可:

@Bean @Primary @ConditionalOnMissingBean(JdbcOperations.class) public JdbcTemplate jdbcTemplate() {JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);JdbcProperties.Template template = this.properties.getTemplate();jdbcTemplate.setFetchSize(template.getFetchSize());jdbcTemplate.setMaxRows(template.getMaxRows());if (template.getQueryTimeout() != null) {jdbcTemplate.setQueryTimeout((int) template.getQueryTimeout().getSeconds());}return jdbcTemplate; }

以上就是Spring Boot默認(rèn)的數(shù)據(jù)訪問(wèn)時(shí)的配置了。

在實(shí)際開(kāi)發(fā)的時(shí)候,我們很少使用org.apache.tomcat.jdbc.pool.DataSource作為我們的數(shù)據(jù)源,這里我給出之前提到過(guò)的切換數(shù)據(jù)源的操作,這里我切換到druid數(shù)據(jù)源,這個(gè)數(shù)據(jù)源有很方便的監(jiān)控的功能,讀者可以作為參照。

首先我們需要在依賴中引入druid數(shù)據(jù)源:

<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version> </dependency>

而后,指定我們的數(shù)據(jù)源類型,并且進(jìn)行數(shù)據(jù)源的配置:

spring:datasource: # 數(shù)據(jù)源基本配置username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/ssm_crudtype: com.alibaba.druid.pool.DruidDataSource # 數(shù)據(jù)源其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true # 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì),'wall'用于防火墻 filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

這里需要注意的時(shí),這里有很多屬性的配置是無(wú)法自動(dòng)配置到DataSourceProperties中的。也就無(wú)法被我們的druid數(shù)據(jù)源使用到,這里我們可以編寫(xiě)我們自己的配置類:

package com.chester.webdemo.config;import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map;@Configuration public class DruidConfig {//這個(gè)注解引入我們?cè)谏厦鎦ml文件中配置的參數(shù)到DruidDataSource數(shù)據(jù)源中@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid監(jiān)控//1.配置一個(gè)管理后臺(tái)的Servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet());Map<String, String> initParams = new HashMap<>();//設(shè)置后臺(tái)監(jiān)控的登陸用戶名initParams.put("loginUsername", "admin");//設(shè)置后臺(tái)監(jiān)控的登陸密碼initParams.put("loginPassword", "123456");//設(shè)置允許訪問(wèn)的地址initParams.put("allow", "");//設(shè)置不允許訪問(wèn)的地址initParams.put("deny", "192.168.15.21");bean.setInitParameters(initParams);return bean;}//2.配置一個(gè)web監(jiān)控Filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String, String> initParams = new HashMap<>();//設(shè)置不攔截的路徑initParams.put("exclusions", "*.js, *.css, /druid/*");bean.setInitParameters(initParams);//設(shè)置監(jiān)控的路徑bean.setUrlPatterns(Arrays.asList("/*"));return bean;} }

如果這個(gè)數(shù)據(jù)源被注入到了容器中,上面說(shuō)的org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource這些數(shù)據(jù)源就不會(huì)繼續(xù)注入了,因?yàn)檫@些數(shù)據(jù)源在自動(dòng)注入容器的時(shí)候有@ConditionalOnMissingBean(DataSource.class)這樣一個(gè)注解。這個(gè)時(shí)候我們可以訪問(wèn)http://localhost:8081/druid 進(jìn)入druid的監(jiān)控界面,填入我們配置好的用戶名,密碼即可。

最后我們整合mybatis,首先我們需要引入mybatis:

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency>

從名字中我們可以知道,這個(gè)包并非Spring官方出品,因?yàn)镾pring的名字更像是這樣spring‐boot‐starter‐*。這個(gè)包實(shí)際上是mybatis出的適配Spring Boot的。接下來(lái)的工作就很簡(jiǎn)單了,因?yàn)镾pring Boot已經(jīng)幫我配置好了,這里依舊給出使用mybatis的示例:

1. 首先創(chuàng)建實(shí)體類:

package com.chester.springboot.bean;public class Department {private Integer id;private String departmentName;public void setId(Integer id) {this.id = id;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}public Integer getId() {return id;}public String getDepartmentName() {return departmentName;} }

2. 創(chuàng)建mapper

package com.chester.springboot.mapper;import com.chester.springboot.bean.Department; import org.apache.ibatis.annotations.*;//指定這是一個(gè)操作數(shù)據(jù)庫(kù)的mapper @Mapper 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的注解的意思是插入后將生成的id封裝到department中,方便我們之后的使用@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); }

這里@Mapper也可以轉(zhuǎn)換為直接在主類上寫(xiě)@MapperScan(value = “com.chester.springboot.mapper”)這個(gè)注解,這樣一來(lái)com.chester.springboot.mapper這個(gè)包下的接口就會(huì)自動(dòng)轉(zhuǎn)換為mapper。

最后編寫(xiě)cotroller使用即可

package com.chester.springboot.controller;import com.atguigu.springboot.bean.Department; import com.atguigu.springboot.bean.Employee; import com.atguigu.springboot.mapper.DepartmentMapper; import com.atguigu.springboot.mapper.EmployeeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;@RestController public class DeptController {@AutowiredDepartmentMapper departmentMapper;@GetMapping("/dept/{id}")public Department getDepartment(@PathVariable("id") Integer id){return departmentMapper.getDeptById(id);}@GetMapping("/dept")public Department insertDept(Department department){departmentMapper.insertDept(department);return department;} }

最后如果我們希望可以對(duì)MyBatis做一些自定義的配置,我們可以像下面這樣寫(xiě)一個(gè)自動(dòng)配置類,這里以開(kāi)啟駝峰命名法為例,或者直接在配置文件中配置:

package com.chester.springboot.config;import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; import org.springframework.context.annotation.Bean;@Configuration public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer(){@Overridepublic void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);}};} }

總結(jié):
在上面的描述中我們討論了Spring Boot的數(shù)據(jù)源的自動(dòng)配置原理,以及自動(dòng)執(zhí)行.sql的原理,我們還講到如何將數(shù)據(jù)源切換到druid,并做好配置,最后我們還講述了如何利用注解使用mybatis。

總結(jié)

以上是生活随笔為你收集整理的Spring Boot数据库操作原理及整合druid数据源和mybatis的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。