柚子快報激活碼778899分享:JavaWeb-MyBatis
柚子快報激活碼778899分享:JavaWeb-MyBatis
目錄
一、MyBatis入門1.1 快速入門1.1.1 創(chuàng)建SpringBoot-MyBatis工程1.1.2 創(chuàng)建數(shù)據(jù)庫1.1.3 加載POM依賴1.1.4 配置Mytabis1.1.5 pojo:編寫用戶實體類1.1.6 service:編寫查詢用戶信息的結(jié)構(gòu)1.1.7 測試1.1.8 默認(rèn)在MyBatis中編寫SQL是沒有提示的,可以做如下配置
1.2 數(shù)據(jù)庫連接池1.3 LomBok
二、MyBatis基礎(chǔ)操作2.1 刪除2.2 新增2.3 修改2.3 查詢2.3.1 根據(jù)ID查詢員工信息2.3.2 模糊查詢
三、XML映射文件3.1 規(guī)范3.2 MybatisX3.3 案例
四、動態(tài)SQL4.1 IF語句4.2 ForEach語句【批量刪除】4.3 `
一、MyBatis入門
1.1 快速入門
1.1.1 創(chuàng)建SpringBoot-MyBatis工程
1.1.2 創(chuàng)建數(shù)據(jù)庫
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : spingboot-mybatis-demo
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 05/01/2024 10:29:12
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`gender` bigint(20) NULL DEFAULT NULL,
`phone` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '張三', 55, 1, '18800000000');
INSERT INTO `user` VALUES (2, '李四', 45, 1, '18800000001');
INSERT INTO `user` VALUES (3, '王五', 38, 1, '18800000002');
INSERT INTO `user` VALUES (4, '趙六', 42, 2, '18800000003');
INSERT INTO `user` VALUES (5, '田七', 37, 1, '18800000004');
INSERT INTO `user` VALUES (6, '劉八', 48, 1, '18800000005');
SET FOREIGN_KEY_CHECKS = 1;
1.1.3 加載POM依賴
1.1.4 配置Mytabis
# 數(shù)據(jù)庫驅(qū)動
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# URL
spring.datasource.url=jdbc:mysql://localhost:3306/spingboot-mybatis-demo
# 用戶名
spring.datasource.username=root
# 密碼
spring.datasource.password=root
注意:如果properties文件中出現(xiàn)中文亂碼
1.1.5 pojo:編寫用戶實體類
省略
1.1.6 service:編寫查詢用戶信息的結(jié)構(gòu)
@Mapper // 在運行時,會自動生成該接口的實現(xiàn)類對象(代理對象),并且將該對象交給IOC容器管理
public interface UserMapper {
/**
* 查詢?nèi)坑脩粜畔?/p>
*/
@Select("select * from user")
public List
}
1.1.7 測試
@SpringBootTest // springboot 整合單元測試的注解
class SpringbootMybatisApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testUserList() {
List
users.forEach(user -> {
System.out.println(user);
});
}
}
1.1.8 默認(rèn)在MyBatis中編寫SQL是沒有提示的,可以做如下配置
如果編寫的SQL語句表名報紅,需要在IDEA中連接數(shù)據(jù)庫
1.2 數(shù)據(jù)庫連接池
數(shù)據(jù)庫連接池是一個容器,負(fù)責(zé)分配,管理數(shù)據(jù)庫連接它允許應(yīng)用程序重復(fù)使用一個現(xiàn)有的數(shù)據(jù)庫連接,而不是再重新建立一個釋放空閑時間超過最大空閑時間的連接,來避免因為沒有釋放連接而引起的數(shù)據(jù)庫連接遺漏優(yōu)點:
資源重用提升系統(tǒng)響應(yīng)速度避免數(shù)據(jù)庫連接遺漏
連接池配置
# 數(shù)據(jù)庫連接池驅(qū)動
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化時建立物理連接的個數(shù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時
spring.datasource.druid.initial-size=10
# 最小連接池數(shù)量
spring.datasource.druid.min-idle=10
# 最大連接池數(shù)量
spring.datasource.druid.max-active=200
# 獲取連接時最大等待時間,單位毫秒。配置了maxWait之后,缺省啟用公平鎖,并發(fā)效率會有所下降,如果需要可以通過配置
spring.datasource.druid.max-wait=60000
# 關(guān)閉空閑連接的檢測時間間隔.Destroy線程會檢測連接的間隔時間,如果連接空閑時間大于等于minEvictableIdleTimeMillis則關(guān)閉物理連接。
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 連接的最小生存時間.連接保持空閑而不被驅(qū)逐的最小時間
spring.datasource.druid.min-evictable-idle-time-millis=300000
# 驗證數(shù)據(jù)庫服務(wù)可用性的sql.用來檢測連接是否有效的sql 因數(shù)據(jù)庫方言而差, 例如 oracle 應(yīng)該寫成 SELECT 1 FROM DUAL
spring.datasource.druid.validation-query=SELECT 1
# 申請連接時檢測空閑時間,根據(jù)空閑時間再檢測連接是否有效.建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRun
spring.datasource.druid.test-while-idle=true
# 申請連接時直接檢測連接是否有效.申請連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。
spring.datasource.druid.test-on-borrow=false
# 歸還連接時檢測連接是否有效.歸還連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。
spring.datasource.druid.test-on-return=false
# 開啟PSCache
spring.datasource.druid.pool-prepared-statements=true
# 設(shè)置PSCache值
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 連接出錯后再嘗試連接三次
spring.datasource.druid.connection-error-retry-attempts=3
# 數(shù)據(jù)庫服務(wù)宕機自動重連機制
spring.datasource.druid.break-after-acquire-failure=true
# 連接出錯后重試時間間隔
spring.datasource.druid.time-between-connect-error-millis=300000
# 異步初始化策略
spring.datasource.druid.async-init=true
# 是否自動回收超時連接
spring.datasource.druid.remove-abandoned=true
# 超時時間(以秒數(shù)為單位)
spring.datasource.druid.remove-abandoned-timeout=1800
# 事務(wù)超時時間
spring.datasource.druid.transaction-query-timeout=6000
# 連接池的過濾器的屬性
spring.datasource.druid.filters=stat,wall,log4j2
# 合并多個DruidDataSource的監(jiān)控數(shù)據(jù)
spring.datasource.druid.use-global-data-source-stat=true
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.druid.connection-properties=druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
1.3 LomBok
通過注解,自動生成構(gòu)造器,getter/setter、equals、hashCode、toString等方法,并且可以自動化生成日志變量,簡化Java開發(fā)、提高效率
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
private Integer gender;
private String phone;
}
二、MyBatis基礎(chǔ)操作
2.1 刪除
@Delete("delete from emp where id= #{id}")
public void deleteEmp(Integer id);
2.2 新增
注意:如果需要新增主鍵返回,需要增加@Options注解
@Options(keyProperty = "id", useGeneratedKeys = true) // 主鍵返回
@Insert("INSERT INTO emp(username,password,name,gender,image,job,entrydate,create_time,update_time,dept_id) " +
"VALUES(#{username}, #{password}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{createTime}, #{updateTime}, #{deptId})")
public void insertEmp(Emp emp);
2.3 修改
@Update("update emp set dept_id=#{deptId}, update_time=#{updateTime} where id=#{id}")
public void updateEmp(Emp emp);
2.3 查詢
注意:如果存在駝峰命名的變量,需要開啟Mybatis的駝峰命名封裝
mybatis.configuration.map-underscore-to-camel-case=true
2.3.1 根據(jù)ID查詢員工信息
@Select("select * from emp where id=#{id}")
public Emp selectEmpById(Integer id);
2.3.2 模糊查詢
方式一:${}
注意:模糊查詢應(yīng)該使用${}傳遞參數(shù),而不是#{}
@Select("select * from emp where name like '%${name}%' and gender=#{gender}")
public List
方式二:concat('%',#{},'%')【推薦使用】
@Select("select * from emp where name like concat('%', #{name}, '%') and gender=#{gender}")
public List
三、XML映射文件
3.1 規(guī)范
XML映射文件的名稱與Mapper接口名稱一致,并且將XML映射文件和Mapper接口放置在相同包下(同包同名)XML映射文件的namespace屬性為Mapper接口全限定名一致XML映射文件中SQL語句的ID與Mapper接口中的方法名一致,并保持返回類型一致。
XML文件約束
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
...
3.2 MybatisX
快速定位XML文件的位置
3.3 案例
select * from emp where name like concat('%', #{name}, '%') and gender=#{gender} order by update_time desc
屬性說明resultType返回值類型:指的是單條記錄所封裝的類型
四、動態(tài)SQL
隨著用戶的輸入或外部條件的變化而變化的SQL語句,我們稱之為動態(tài)SQL
4.1 IF語句
select * from emp
name like concat('%', #{name}, '%')
and gender=#{gender}
order by update_time desc
update emp
dept_id=#{deptId},
update_time=#{updateTime}
id = #{id}
4.2 ForEach語句【批量刪除】
delete from emp
id in
#{id}
屬性說明collection遍歷的集合item遍歷出來的元素separator分隔符open遍歷之前拼接的SQL片段close遍歷結(jié)束后拼接的SQL片段
4.3
SQL片段的抽取和引用,一般聯(lián)合使用
id,username,password,name,gender,image,job,entrydate,create_time,update_time,dept_id
select
from emp
柚子快報激活碼778899分享:JavaWeb-MyBatis
相關(guān)閱讀
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。