#SpringBoot# 數據庫操作之整合Mybaties和事務

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

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

SpringBoot整合Mybatis實操和打印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();
	}

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

什麼是數據庫事務,常見的隔離級別和傳播行爲

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

2、講解場景的隔離級別
	Serializable: 最嚴格,串行處理,消耗資源大
	Repeatable Read:保證了一個事務不會修改已經由另一個事務讀取但未提交(回滾)的數據
	Read Committed:大多數主流數據庫的默認事務等級
	Read Uncommitted:保證了讀取過程中不會讀取到非法數據。
	
3、講解常見的傳播行爲
	PROPAGATION_REQUIRED--支持當前事務,如果當前沒有事務,就新建一個事務,最常見的選擇。

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

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

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

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

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

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();
	}

在這裏插入圖片描述
公衆號: 自學it的攻城獅(id:study458)

發佈了59 篇原創文章 · 獲贊 4 · 訪問量 5112
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章