1. 程式人生 > >小D課堂【SpringBoot】數據庫操作之整合Mybaties和事務講解

小D課堂【SpringBoot】數據庫操作之整合Mybaties和事務講解

nod 單點 bsp long app 實操 www tin 手機

========================8、數據庫操作之整合Mybaties和事務講解 5節課================================

加入小D課堂技術交流答疑群:Q群:699347262

1、SpringBoot2.x持久化數據方式介紹

簡介:介紹近幾年常用的訪問數據庫的方式和優缺點

1、原始java訪問數據庫
開發流程麻煩
1、註冊驅動/加載驅動
Class.forName("com.mysql.jdbc.Driver")
2、建立連接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");

3、創建Statement

4、執行SQL語句

5、處理結果集

6、關閉連接,釋放資源

2、apache dbutils框架
比上一步簡單點
官網:https://commons.apache.org/proper/commons-dbutils/
3、jpa框架
spring-data-jpa
jpa在復雜查詢的時候性能不是很好

4、Hiberante 解釋:ORM:對象關系映射Object Relational Mapping
企業大都喜歡使用hibernate

5、Mybatis框架
互聯網行業通常使用mybatis

不提供對象和關系模型的直接映射,半ORM

2、SpringBoot2.x整合Mybatis3.x註解實戰
簡介:SpringBoot2.x整合Mybatis3.x註解配置實戰

1、使用starter, maven倉庫地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter

2、加入依賴(可以用 http://start.spring.io/ 下載)

<!-- 引入starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
<scope>runtime</scope>
</dependency>

<!-- MySQL的JDBC驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入第三方數據源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

3、加入配置文件
#mybatis.type-aliases-package=net.xdclass.base_project.domain
#可以自動識別
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =password
#如果不使用默認的數據源 (com.zaxxer.hikari.HikariDataSource)
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource

加載配置,註入到sqlSessionFactory等都是springBoot幫我們完成

4、啟動類增加mapper掃描
@MapperScan("net.xdclass.base_project.mapper")

技巧:保存對象,獲取數據庫自增id
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")

4、開發mapper
參考語法 http://www.mybatis.org/mybatis-3/zh/java-api.html

5、sql腳本
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT ‘名稱‘,
`phone` varchar(16) DEFAULT NULL COMMENT ‘用戶手機號‘,
`create_time` datetime DEFAULT NULL COMMENT ‘創建時間‘,
`age` int(4) DEFAULT NULL COMMENT ‘年齡‘,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;


相關資料:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples

整合問題集合:
https://my.oschina.net/hxflar1314520/blog/1800035
https://blog.csdn.net/tingxuetage/article/details/80179772

3、SpringBoot2.x整合Mybatis3.x增刪改查實操和控制臺打印SQL語句
講解:SpringBoot2.x整合Mybatis3.x增刪改查實操, 控制臺打印sql語句

1、控制臺打印sql語句
#增加打印sql語句,一般用於本地開發測試
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

2、增加mapper代碼
@Select("SELECT * FROM user")
@Results({
@Result(column = "create_time",property = "createTime") //javaType = java.util.Date.class
})
List<User> getAll();

@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(column = "create_time",property = "createTime")
})
User findById(Long id);

@Update("UPDATE user SET name=#{name} WHERE id =#{id}")
void update(User user);

@Delete("DELETE FROM user WHERE id =#{userId}")
void delete(Long userId);

3、增加API

@GetMapping("find_all")
public Object findAll(){
return JsonData.buildSuccess(userMapper.getAll());
}

@GetMapping("find_by_Id")
public Object findById(long id){
return JsonData.buildSuccess(userMapper.findById(id));
}

@GetMapping("del_by_id")
public Object delById(long id){
userMapper.delete(id);
return JsonData.buildSuccess();
}

@GetMapping("update")
public Object update(String name,int id){
User user = new User();
user.setName(name);
user.setId(id);
userMapper.update(user);
return JsonData.buildSuccess();
}


4、事務介紹和常見的隔離級別,傳播行為

簡介:講解什麽是數據庫事務,常見的隔離級別和傳播行為

1、介紹什麽是事務,單機事務,分布式事務處理等

2、講解場景的隔離級別
Serializable: 最嚴格,串行處理,消耗資源大
Repeatable Read:保證了一個事務不會修改已經由另一個事務讀取但未提交(回滾)的數據
Read Committed:大多數主流數據庫的默認事務等級
Read Uncommitted:保證了讀取過程中不會讀取到非法數據。


3、講解常見的傳播行為
PROPAGATION_REQUIRED--支持當前事務,如果當前沒有事務,就新建一個事務,最常見的選擇。

PROPAGATION_SUPPORTS--支持當前事務,如果當前沒有事務,就以非事務方式執行。

PROPAGATION_MANDATORY--支持當前事務,如果當前沒有事務,就拋出異常。

PROPAGATION_REQUIRES_NEW--新建事務,如果當前存在事務,把當前事務掛起, 兩個事務之間沒有關系,一個異常,一個提交,不會同時回滾

PROPAGATION_NOT_SUPPORTED--以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。

PROPAGATION_NEVER--以非事務方式執行,如果當前存在事務,則拋出異常

5、SpringBoot整合mybatis之事務處理實戰
簡介:SpringBoot整合Mybatis之事務處理實戰
1、service邏輯引入事務 @Transantional(propagation=Propagation.REQUIRED)

2、service代碼
@Override
@Transactional
public int addAccount() {
User user = new User();
user.setAge(9);
user.setCreateTime(new Date());
user.setName("事務測試");
user.setPhone("000121212");

userMapper.insert(user);
int a = 1/0;

return user.getId();
}

小D課堂【SpringBoot】數據庫操作之整合Mybaties和事務講解