Hello,今天給各位童鞋們分享Spring Boot轿亮,趕緊拿出小本子記下來吧疮薇!
Spring Boot 整合 Druid
概述
Druid 是阿里巴巴開源平臺上的一個項目,整個項目由數(shù)據(jù)庫連接池我注、插件框架和 SQL 解析器組成按咒。該項目主要是為了擴展 JDBC 的一些限制,可以讓程序員實現(xiàn)一些特殊的需求仓手,比如向密鑰服務請求憑證胖齐、統(tǒng)計 SQL 信息、SQL 性能收集嗽冒、SQL 注入檢查、SQL 翻譯等补履,程序員可以通過定制來實現(xiàn)自己需要的功能添坊。
Druid 是目前最好的數(shù)據(jù)庫連接池,在功能箫锤、性能贬蛙、擴展性方面,都超過其他數(shù)據(jù)庫連接池谚攒,包括 DBCP阳准、C3P0、BoneCP馏臭、Proxool野蝇、JBoss DataSource。Druid 已經(jīng)在阿里巴巴部署了超過 600 個應用括儒,經(jīng)過多年生產(chǎn)環(huán)境大規(guī)模部署的嚴苛考驗绕沈。Druid 是阿里巴巴開發(fā)的號稱為監(jiān)控而生的數(shù)據(jù)庫連接池!
引入依賴
在 pom.xml 文件中引入 druid-spring-boot-starter 依賴
<dependency>
? ? <groupId>com.alibaba</groupId>
? ? <artifactId>druid-spring-boot-starter</artifactId>
? ? <version>1.1.10</version>
</dependency>
引入數(shù)據(jù)庫連接依賴
? ? <groupId>mysql</groupId>
? ? <artifactId>mysql-connector-java</artifactId>
? ? <scope>runtime</scope>
配置 application.yml
在 application.yml中配置數(shù)據(jù)庫連接
spring:
? datasource:
url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false
? ? username: root
? ? password: 123456
? ? type: com.alibaba.druid.pool.DruidDataSource
? ? initial-size: 1
? ? min-idle: 1
? ? max-active: 20
? ? test-on-borrow: true
? ? # MySQL 8.x: com.mysql.cj.jdbc.Driver
? ? driver-class-name: com.mysql.jdbc.Driver
MySQL服務使用docker容器開啟
Spring Boot 整合 tk.mybatis
tk.mybatis 是在 MyBatis 框架的基礎上提供了很多工具帮寻,讓開發(fā)更加高效
在 pom.xml 文件中引入 mapper-spring-boot-starter 依賴乍狐,該依賴會自動引入MyBaits 相關依賴
? ? <groupId>tk.mybatis</groupId>
? ? <artifactId>mapper-spring-boot-starter</artifactId>
? ? <version>2.0.2</version>
配置 MyBatis
mybatis:
? ? ? ?type-aliases-package: 實體類的存放路徑,如:com.zysheep.spring.boot.mybatis.entity
? ? mapper-locations: classpath:mapper/*.xml
創(chuàng)建一個通用的父級接口
主要作用是讓 DAO層的接口繼承該接口固逗,以達到使用 tk.mybatis的目的,特別注意:該接口不能被掃描到浅蚪,否則會出錯
package tk.mybatis;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
?*自己的 Mapper
?* @author :zysheep
?* @date :Created in 2020/1/11 22:49
?* @description:${description}
?* @version: ${version}$
?*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
Spring Boot 整合 PageHelper
PageHelper 是 Mybatis 的分頁插件藕帜,支持多數(shù)據(jù)庫、多數(shù)據(jù)源惜傲∏⒐剩可以簡化數(shù)據(jù)庫的分頁查詢操作,整合過程也極其簡單操漠,只需引入依賴即可收津。
在 pom.xml 文件中引入 pagehelper-spring-boot-starter 依賴
? ? <groupId>com.github.pagehelper</groupId>
? ? <artifactId>pagehelper-spring-boot-starter</artifactId>
? ? <version>1.2.5</version>
使用 MyBatis 的 Maven 插件生成代碼
我們無需手動編寫 實體類、DAO浊伙、XML 配置文件撞秋,只需要使用 MyBatis 提供的一個 Maven 插件就可以自動生成所需的各種文件便能夠滿足基本的業(yè)務需求,如果業(yè)務比較復雜只需要修改相關文件即可嚣鄙。
配置插件
在pom.xml 文件中增加mybatis-generator-maven-plugin 插件,configurationFile:自動生成所需的配置文件路徑
自動生成的配置
在 src/main/resources/generator/目錄下創(chuàng)建 generatorConfig.xml
?配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
? ? ? ? PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
? ? ? ? "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
? ? <!-- 引入數(shù)據(jù)庫連接配置 -->
? ? <properties resource="jdbc.properties"/>
? ? <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
? ? ? ? <property name="beginningDelimiter" value="`"/>
? ? ? ? <property name="endingDelimiter" value="`"/>
? ? ? ? <!-- 配置 tk.mybatis 插件-->
? ? ? ? <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
? ? ? ? ? ? <property name="mappers" value="cn.tk.mybatis.MyMapper"/>
? ? ? ? </plugin>
? ? ? ? <!-- 配置數(shù)據(jù)庫連接 -->
? ? ? ? <jdbcConnection
? ? ? ? ? ? ? ? driverClass="${jdbc.driverClass}"
? ? ? ? ? ? ? ? connectionURL="${jdbc.connectionURL}"
? ? ? ? ? ? ? ? userId="${jdbc.username}"
? ? ? ? ? ? ? ? password="${jdbc.password}">
? ? ? ? </jdbcConnection>
? ? ? ? <!-- 配置實體類存放路徑 -->
? ? ? ? <javaModelGenerator targetPackage="cn.panyucable.pojo" targetProject="src/main/java"/>
? ? ? ? <!-- 配置 XML 存放路徑 -->
? ? ? ? <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
? ? ? ? <!-- 配置 DAO 存放路徑 -->
? ? ? ? <javaClientGenerator
? ? ? ? ? ? ? ? targetPackage="cn.panyucable.mapper"
? ? ? ? ? ? ? ? targetProject="src/main/java"
? ? ? ? ? ? ? ? type="XMLMAPPER"/>
? ? ? ? <!-- 配置需要指定生成的數(shù)據(jù)庫和表吻贿,% 代表所有表 -->
? ? ? ? <table catalog="panyucable_cn" tableName="%">
? ? ? ? ? ? <!-- mysql 配置 -->
? ? ? ? ? ? <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
? ? ? ? </table>
? ? </context>
</generatorConfiguration>
配置數(shù)據(jù)源
在 src/main/resources目錄下創(chuàng)建 jdbc.properties
?數(shù)據(jù)源配置:
# MySQL 8.x: com.mysql.cj.jdbc.Driver
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root
插件自動生成命令
mvn mybatis-generator:generate
測試 MyBatis 操作數(shù)據(jù)庫
使用 tk.mybatis 操作數(shù)據(jù)庫
修改入口類
創(chuàng)建測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class)
@Transactional
@Rollback
public class MyBatisTests {
? ? /**
? ? ?* 注入數(shù)據(jù)查詢接口
? ? ?*/
? ? @Autowired
? ? private TbUserMapper tbUserMapper;
? ? ?* 測試插入數(shù)據(jù)
? ? @Test
? ? public void testInsert() {
? ? ? ? // 構造一條測試數(shù)據(jù)
? ? ? ? TbUser tbUser = new TbUser();
? ? ? ? tbUser.setUsername("Lusifer");
? ? ? ? tbUser.setPassword("123456");
? ? ? ? tbUser.setPhone("15888888888");
? ? ? ? tbUser.setEmail("topsale@vip.qq.com");
? ? ? ? tbUser.setCreated(new Date());
? ? ? ? tbUser.setUpdated(new Date());
? ? ? ? // 插入數(shù)據(jù)
? ? ? ? tbUserMapper.insert(tbUser);
? ? }
? ? ?* 測試刪除數(shù)據(jù)
? ? public void testDelete() {
? ? ? ? // 構造條件,等同于 DELETE from tb_user WHERE username = 'Lusifer'
? ? ? ? Example example = new Example(TbUser.class);
? ? ? ? example.createCriteria().andEqualTo("username", "Lusifer");
? ? ? ? //刪除數(shù)據(jù)
? ? ? ? tbUserMapper.deleteByExample(example);
? ? ?* 測試修改數(shù)據(jù)
? ? public void testUpdate() {
? ? ? ? // 構造條件
? ? ? ? tbUser.setUsername("LusiferNew");
? ? ? ? // 修改數(shù)據(jù)
? ? ? ? tbUserMapper.updateByExample(tbUser, example);
? ? ?* 測試查詢集合
? ? public void testSelect() {
? ? ? ? List<TbUser> tbUsers = tbUserMapper.selectAll();
? ? ? ? for (TbUser tbUser : tbUsers) {
? ? ? ? ? ? System.out.println(tbUser.getUsername());
? ? ? ? }
? ? ?* 測試分頁查詢
? ? public void testPage() {
? ? ? ? // PageHelper 使用非常簡單哑子,只需要設置頁碼和每頁顯示筆數(shù)即可
? ? ? ? PageHelper.startPage(0, 2);
? ? ? ? // 設置分頁查詢條件
? ? ? ? PageInfo<TbUser> pageInfo = new PageInfo<>(tbUserMapper.selectByExample(example));
? ? ? ? // 獲取查詢結果
? ? ? ? List<TbUser> tbUsers = pageInfo.getList();
? ? //當前頁
? ? private int pageNum;
? ? //每頁的數(shù)量
? ? private int pageSize;
? ? //當前頁的數(shù)量
? ? private int size;
? ? //由于startRow和endRow不常用舅列,這里說個具體的用法
? ? //可以在頁面中"顯示startRow到endRow 共size條數(shù)據(jù)"
? ? //當前頁面第一個元素在數(shù)據(jù)庫中的行號
? ? private int startRow;
? ? //當前頁面最后一個元素在數(shù)據(jù)庫中的行號
? ? private int endRow;
? ? //總記錄數(shù)
? ? private long total;
? ? //總頁數(shù)
? ? private int pages;
? ? //結果集
? ? private List<T> list;
? ? //前一頁
? ? private int prePage;
? ? //下一頁
? ? private int nextPage;
? ? //是否為第一頁
? ? private boolean isFirstPage = false;
? ? //是否為最后一頁
? ? private boolean isLastPage = false;
? ? //是否有前一頁
? ? private boolean hasPreviousPage = false;
? ? //是否有下一頁
? ? private boolean hasNextPage = false;
? ? //導航頁碼數(shù)
? ? private int navigatePages;
? ? //所有導航頁號
? ? private int[] navigatepageNums;
? ? //導航條上的第一頁
? ? private int navigateFirstPage;
? ? //導航條上的最后一頁
? ? private int navigateLastPage;
TkMybatis的常用方法介紹
Select
List select(T record);
根據(jù)實體中的屬性值進行查詢,查詢條件使用等號
T selectByPrimaryKey(Object key);
根據(jù)主鍵字段進行查詢卧蜓,方法參數(shù)必須包含完整的主鍵屬性帐要,查詢條件使用等號
List selectAll();
查詢?nèi)拷Y果,select(null)方法能達到同樣的效果
T selectOne(T record);
根據(jù)實體中的屬性進行查詢弥奸,只能有一個返回值榨惠,有多個結果是拋出異常,查詢條件使用等號
int selectCount(T record);
根據(jù)實體中的屬性查詢總數(shù)盛霎,查詢條件使用等號
Insert
int insert(T record);
保存一個實體赠橙,null的屬性也會保存,不會使用數(shù)據(jù)庫默認值
int insertSelective(T record);
保存一個實體愤炸,null的屬性不會保存期揪,會使用數(shù)據(jù)庫默認值
Update
int updateByPrimaryKey(T record);
根據(jù)主鍵更新實體全部字段,null值會被更新
int updateByPrimaryKeySelective(T record);
根據(jù)主鍵更新屬性不為null的值
Delete
int delete(T record);
根據(jù)實體屬性作為條件進行刪除规个,查詢條件使用等號
int deleteByPrimaryKey(Object key);
根據(jù)主鍵字段進行刪除凤薛,方法參數(shù)必須包含完整的主鍵屬性
Example方法
List selectByExample(Object example);
根據(jù)Example條件進行查詢
重點: 這個查詢支持通過 Example 類指定查詢列,通過 selectProperties 方法指定查詢列
int selectCountByExample(Object example);
根據(jù)Example條件進行查詢總數(shù)
int updateByExample(@Param(“record”) T record, @Param(“example”) Object example);
根據(jù)Example條件更新實體 record 包含的全部屬性绰姻,null值會被更新
int updateByExampleSelective(@Param(“record”) T record, @Param(“example”) Object example);
根據(jù)Example條件更新實體 record 包含的不是null的屬性值
int deleteByExample(Object example);
根據(jù)Example條件刪除數(shù)據(jù)
Example 使用方法詳解
Example用于添加條件枉侧,相當where后面的部分
作用:
example
用來放一些去重,排序狂芋,分類榨馁,分頁等信息
criteria
用來傳字段參數(shù)
常用的方法及使用說明:
首先進行初始化:?
Example example = new Example(實體類.class);
Example.Criteria criteria = example.createCriteria();
添加升序排列條件,DESC為降序:
example.setOrderByClause("字段名 ASC");
去除重復帜矾,boolean型翼虫,true為選擇不重復的記錄:
example.setDistinct(false)
添加字段xxx為null的條件:
criteria.andXxxIsNull
添加字段xxx不為null的條件:
criteria.andXxxIsNotNull
添加xxx字段等于value條件:
criteria.andXxxEqualTo(value)
添加xxx字段不等于value條件:
criteria.andXxxNotEqualTo(value)
添加xxx字段大于value條件:
criteria.andXxxGreaterThan(value)
添加xxx字段大于等于value條件:
criteria.andXxxGreaterThanOrEqualTo(value)
添加xxx字段小于value條件:
criteria.andXxxLessThan(value)
添加xxx字段小于等于value條件:
criteria.andXxxLessThanOrEqualTo(value)
添加xxx字段值在List<屑柔?>條件:
criteria.andXxxIn(List<?>)
添加xxx字段值不在List<珍剑?>條件:
criteria.andXxxNotIn(List<掸宛?>)
添加xxx字段值為value的模糊查詢條件:
criteria.andXxxLike("%"+value+"%")
添加xxx字段值不為value的模糊查詢條件:
criteria.andXxxNotLike("%"+value+"%"")
添加xxx字段值在value1和value2之間條件:
criteria.andXxxBetween(value1,value2)
添加xxx字段值不在value1和value2之間條件:
criteria.andXxxNotBetween(value1,value2)
需要注意的點:
首先要生成實例化及實例對應的example,然后記住一定要先初始化;
使用and和or方法進行判斷時招拙,“與”唧瘾、“或”的邏輯關系分清,避免出現(xiàn)拿數(shù)據(jù)時出現(xiàn)重復拿或者邏輯沖突拿不到的情況;
mapper.selectByExample()方法里面應該傳入的參數(shù)是example對象,而非其他的别凤。
附:完整的 POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? ? ?xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
? ? <modelVersion>4.0.0</modelVersion>
? ? <parent>
? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? <artifactId>spring-boot-starter-parent</artifactId>
? ? ? ? <version>2.2.2.RELEASE</version>
? ? ? ? <relativePath/> <!-- lookup parent from repository -->
? ? </parent>
? ? <groupId>com.zysheep</groupId>
? ? <artifactId>spring-boot-mybatis</artifactId>
? ? <version>1.0.0-SNAPSHOT</version>
? ? <name>spring-boot-mybatis</name>
? ? <description>Demo project for Spring Boot</description>
? ? <properties>
? ? ? ? <java.version>1.8</java.version>
? ? </properties>
? ? <dependencies>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId>
? ? ? ? </dependency>
? ? ? ? ? ? <artifactId>spring-boot-starter-web</artifactId>
? ? ? ? ? ? <artifactId>spring-boot-starter-test</artifactId>
? ? ? ? ? ? <scope>test</scope>
? ? ? ? ? ? <exclusions>
? ? ? ? ? ? ? ? <exclusion>
? ? ? ? ? ? ? ? ? ? <groupId>org.junit.vintage</groupId>
? ? ? ? ? ? ? ? ? ? <artifactId>junit-vintage-engine</artifactId>
? ? ? ? ? ? ? ? </exclusion>
? ? ? ? ? ? </exclusions>
? ? ? ? ? ? <groupId>com.alibaba</groupId>
? ? ? ? ? ? <artifactId>druid-spring-boot-starter</artifactId>
? ? ? ? ? ? <version>1.1.10</version>
? ? ? ? ? ? <groupId>mysql</groupId>
? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>
? ? ? ? ? ? <scope>runtime</scope>
? ? ? ? ? ? <groupId>tk.mybatis</groupId>
? ? ? ? ? ? <artifactId>mapper-spring-boot-starter</artifactId>
? ? ? ? ? ? <version>2.0.2</version>
? ? ? ? ? ? <groupId>com.github.pagehelper</groupId>
? ? ? ? ? ? <artifactId>pagehelper-spring-boot-starter</artifactId>
? ? ? ? ? ? <version>1.2.5</version>
? ? ? ? ? ? <groupId>junit</groupId>
? ? ? ? ? ? <artifactId>junit</artifactId>
? ? ? ? ? ? <version>4.12</version>
? ? </dependencies>
? ? <build>
? ? ? ? <plugins>
? ? ? ? ? ? <plugin>
? ? ? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ? <artifactId>spring-boot-maven-plugin</artifactId>
? ? ? ? ? ? </plugin>
? ? ? ? ? ? ? ? <groupId>org.mybatis.generator</groupId>
? ? ? ? ? ? ? ? <artifactId>mybatis-generator-maven-plugin</artifactId>
? ? ? ? ? ? ? ? <version>1.3.5</version>
? ? ? ? ? ? ? ? <configuration>
? ? ? ? ? ? ? ? ? ? <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
? ? ? ? ? ? ? ? ? ? <overwrite>true</overwrite>
? ? ? ? ? ? ? ? ? ? <verbose>true</verbose>
? ? ? ? ? ? ? ? </configuration>
? ? ? ? ? ? ? ? <dependencies>
? ? ? ? ? ? ? ? ? ? <dependency>
? ? ? ? ? ? ? ? ? ? ? ? <groupId>mysql</groupId>
? ? ? ? ? ? ? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>
? ? ? ? ? ? ? ? ? ? ? ? <version>${mysql.version}</version>
? ? ? ? ? ? ? ? ? ? </dependency>
? ? ? ? ? ? ? ? ? ? ? ? <groupId>tk.mybatis</groupId>
? ? ? ? ? ? ? ? ? ? ? ? <artifactId>mapper</artifactId>
? ? ? ? ? ? ? ? ? ? ? ? <version>3.4.4</version>
? ? ? ? ? ? ? ? </dependencies>
? ? ? ? </plugins>
? ? </build>
</project>
好啦饰序,今天的文章就到這里,希望能幫助到屏幕前迷茫的你們规哪!