偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

教小師妹快速入門Mybatis,看這篇就夠了

開發(fā) 后端
什么是ORM?全稱為Object Relational Mapping。對象-映射-關(guān)系型數(shù)據(jù)庫。

[[356483]]

本文主要內(nèi)容:

 

傳統(tǒng)JDBC

傳統(tǒng)JDBC編碼格式

  1. public class DataBaseUtil { 
  2.     public static final String URL = "jdbc:mysql://localhost:3306/mblog"
  3.     public static final String USER = "root"
  4.     public static final String PASSWORD = "123456"
  5.  
  6.     public static void main(String[] args) throws Exception { 
  7.          
  8.         Class.forName("com.mysql.jdbc.Driver"); 
  9.         //2.  
  10.         Connection conn = DriverManager.getConnection(URL, USERPASSWORD); 
  11.         //3. 
  12.         Statement stmt = conn.createStatement(); 
  13.         //4. 
  14.         ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM m_user where id =1"); 
  15.         //如果有數(shù)據(jù),rs.next()返回true 
  16.         while(rs.next()){ 
  17.             System.out.println("name: "+rs.getString("name")+" 年齡:"+rs.getInt("age")); 
  18.         } 
  19.     } 

上面代碼中知識為了展示JDBC整個過程(異常和資源是簡單粗暴的處理了,我們關(guān)注的點(diǎn)不在這兩個)。

大致可以分為六個步驟:

  • 加載驅(qū)動程序
  • 獲得數(shù)據(jù)庫連接
  • 創(chuàng)建一個Statement對象
  • 操作數(shù)據(jù)庫,實現(xiàn)增刪改查
  • 獲取結(jié)果集
  • 關(guān)閉資源

從使用層面來說,采用原生態(tài)的JDBC在項目中使用起來成本還是很高的。如果我們的項目中的業(yè)務(wù)相對比較復(fù)雜,數(shù)據(jù)庫表也相對較多,各種操作數(shù)據(jù)庫的增刪改查的方法也會隨之多起來,那么這樣的代碼重復(fù)次數(shù)會非常之多。

傳統(tǒng)JDBC的問題

  • 創(chuàng)建數(shù)據(jù)庫的連接存在大量的硬編碼,
  • 執(zhí)行statement時存在硬編碼.
  • 頻繁的開啟和關(guān)閉數(shù)據(jù)庫連接,會嚴(yán)重影響數(shù)據(jù)庫的性能,浪費(fèi)數(shù)據(jù)庫的資源.
  • 存在大量的重復(fù)性編碼

為了解決以上問題,就誕生了各種各樣替換JDBC的產(chǎn)品。即就是ORM框架。

什么是ORM?

全稱為Object Relational Mapping。對象-映射-關(guān)系型數(shù)據(jù)庫。對象關(guān)系映射(,簡稱ORM,或O/RM,或O/R mapping),用于實現(xiàn)面向?qū)ο缶幊陶Z言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換。簡單的說,ORM是通過使用描述對象和數(shù)據(jù)庫之間映射的元數(shù)據(jù),將程序中的對象與關(guān)系數(shù)據(jù)庫相互映射。

ORM提供了實現(xiàn)持久化層的另一種模式,它采用映射元數(shù)據(jù)來描述對象關(guān)系的映射,使得ORM中間件能在任何一個應(yīng)用的業(yè)務(wù)邏輯層和數(shù)據(jù)庫層之間充當(dāng)橋梁。

 

我們的項目中是這樣的:

 

比如說:Apache DbUtils、Spring JDBC、 Hibernate、Ibatis(Mybatis的前生)、Spring Data Jpa等等。

目前最為流行的Mybatis和Spring Data Jpa。本系列我們先講解Mybatis,Jpa后面再講。

ORM的優(yōu)缺點(diǎn)

優(yōu)點(diǎn)1.提高了開發(fā)效率。由于ORM可以自動對Entity對象與數(shù)據(jù)庫中的Table進(jìn)行字段與屬性的映射,所以我們實際可能已經(jīng)不需要一個專用的、龐大的數(shù)據(jù)訪問層。2.ORM提供了對數(shù)據(jù)庫的映射,不用sql直接編碼,能夠像操作對象一樣從數(shù)據(jù)庫獲取數(shù)據(jù)。

缺點(diǎn)犧牲程序的執(zhí)行效率和會固定思維模式,降低了開發(fā)的靈活性。

從系統(tǒng)結(jié)構(gòu)上來看,采用ORM的系統(tǒng)一般都是多層系統(tǒng),系統(tǒng)的層次多了,效率就會降低。ORM是一種完全的面向?qū)ο蟮淖龇?,而面向?qū)ο蟮淖龇ㄒ矔π阅墚a(chǎn)生一定的影響。在我們開發(fā)系統(tǒng)時,一般都有性能問題。性能問題主要產(chǎn)生在算法不正確和與數(shù)據(jù)庫不正確的使用上。ORM所生成的代碼一般不太可能寫出很高效的算法,在數(shù)據(jù)庫應(yīng)用上更有可能會被誤用,主要體現(xiàn)在對持久對象的提取和和數(shù)據(jù)的加工處理上,如果用上了ORM,程序員很有可能將全部的數(shù)據(jù)提取到內(nèi)存對象中,然后再進(jìn)行過濾和加工處理,這樣就容易產(chǎn)生性能問題。在對對象做持久化時,ORM一般會持久化所有的屬性,有時,這是不希望的。但ORM是一種工具,工具確實能解決一些重復(fù),簡單的勞動。這是不可否認(rèn)的。但我們不能指望工具能一勞永逸的解決所有問題,有些問題還是需要特殊處理的,但需要特殊處理的部分對絕大多數(shù)的系統(tǒng),應(yīng)該是很少的。

MyBatis 是什么?

如果在面試的時候被問到,只要你說出下面三種即可。

MyBatis 是一款優(yōu)秀的持久層框架,它支持自定義 SQL、存儲過程以及高級映射。

MyBatis 免除了幾乎所有的 JDBC 代碼以及設(shè)置參數(shù)和獲取結(jié)果集的工作。

MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數(shù)據(jù)庫中的記錄。

來自官網(wǎng)。

MyBatis的優(yōu)點(diǎn)和缺點(diǎn)

優(yōu)點(diǎn):

(1)基于SQL語句編程,相當(dāng)靈活,不會對應(yīng)用程序或者數(shù)據(jù)庫的現(xiàn)有設(shè)計造成任何影響,SQL寫在XML里,解除sql與程序代碼的耦合,便于統(tǒng)一管理;提供XML標(biāo)簽,支持編寫動態(tài)SQL語句,并可重用。

(2)與JDBC相比,減少了50%以上的代碼量,消除了JDBC大量冗余的代碼,不需要手動開關(guān)連接;

(3)很好的與各種數(shù)據(jù)庫兼容(因為MyBatis使用JDBC來連接數(shù)據(jù)庫,所以只要JDBC支持的數(shù)據(jù)庫MyBatis都支持)。

(4)能夠與Spring很好的集成;

(5)提供映射標(biāo)簽,支持對象與數(shù)據(jù)庫的ORM字段關(guān)系映射;提供對象關(guān)系映射標(biāo)簽,支持對象關(guān)系組件維護(hù)。

缺點(diǎn)

(1)SQL語句的編寫工作量較大,尤其當(dāng)字段多、關(guān)聯(lián)表多時,對開發(fā)人員編寫SQL語句的功底有一定要求。

(2)SQL語句依賴于數(shù)據(jù)庫,導(dǎo)致數(shù)據(jù)庫移植性差,不能隨意更換數(shù)據(jù)庫。

Mybatis環(huán)境搭建及簡單實例

創(chuàng)建一張數(shù)據(jù)庫表

創(chuàng)建一張m_user表使用MySQL數(shù)據(jù)庫。

  1. CREATE TABLE `m_user` ( 
  2.   `id` int(11) NOT NULL AUTO_INCREMENT, 
  3.   `namevarchar(255) DEFAULT NULL
  4.   `age` int(11) DEFAULT NULL
  5.   PRIMARY KEY (`id`) 
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 

添加依賴

  1. <dependency> 
  2.             <groupId>org.mybatis</groupId> 
  3.             <artifactId>mybatis</artifactId> 
  4.             <version>3.5.2</version> 
  5.         </dependency> 
  6.         <dependency> 
  7.             <groupId>mysql</groupId> 
  8.             <artifactId>mysql-connector-java</artifactId> 
  9.             <version>8.0.16</version> 
  10.             <scope>runtime</scope> 
  11.         </dependency> 
  12. </dependencies> 

項目結(jié)構(gòu)如下:

 

創(chuàng)建一個mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE configuration 
  3.         PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  4.         "http://mybatis.org/dtd/mybatis-3-config.dtd"
  5. <configuration> 
  6.     <environments default="development"
  7.         <environment id="development"
  8.             <transactionManager type="JDBC"/> 
  9.             <dataSource type="POOLED"
  10.                 <property name="driver" value="com.mysql.cj.jdbc.Driver"/> 
  11.                 <property name="url" value="jdbc:mysql://localhost:3306/mblog?useUnicode=true"/> 
  12.                 <property name="username" value="root"/> 
  13.                 <property name="password" value="123456"/> 
  14.             </dataSource> 
  15.         </environment> 
  16.     </environments> 
  17.     <mappers> 
  18.         <mapper resource="mapper/UserMapper.xml"/> 
  19.     </mappers> 
  20. </configuration> 

實體類User

  1. ublic class User { 
  2.     private Integer id; 
  3.     private String name
  4.     private Integer age; 
  5.     //set get 
  6.     @Override 
  7.     public String toString() { 
  8.         return "User{" + 
  9.                 "id=" + id + 
  10.                 ", name='" + name + '\'' + 
  11.                 ", age=" + age + 
  12.                 '}'
  13.     } 

創(chuàng)建UserMapper.java

  1. import com.tian.mybatis.entity.User
  2.  
  3. public interface UserMapper { 
  4.     User selectUserById(Integer id); 

創(chuàng)建UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE mapper 
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
  4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
  5. <mapper namespace="com.tian.mybatis.mapper.UserMapper"
  6.     <select id="selectUserById" resultType="com.tian.mybatis.entity.User"
  7.         select * from m_user where id = #{id} 
  8.     </select
  9. </mapper> 

創(chuàng)建一個測試類

  1. import com.tian.mybatis.entity.User
  2. import org.apache.ibatis.io.Resources; 
  3. import org.apache.ibatis.session.SqlSession; 
  4. import org.apache.ibatis.session.SqlSessionFactory; 
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  6.  
  7. import java.io.IOException; 
  8. import java.io.InputStream; 
  9.  
  10. public class MybatisApplication { 
  11.  
  12.  public static void main(String[] args) { 
  13.         String resource = "mybatis-config.xml"
  14.         InputStream inputStream = null
  15.         SqlSession sqlSession =null
  16.         try { 
  17.             inputStream = Resources.getResourceAsStream(resource); 
  18.             //工廠模式 
  19.             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
  20.             //sql操作會話 
  21.             sqlSession = sqlSessionFactory.openSession(); 
  22.             //獲取數(shù)據(jù)并解析成User對象 
  23.             User user = sqlSession.selectOne("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); 
  24.             System.out.println(user); 
  25.         } catch (Exception e) { 
  26.             e.printStackTrace(); 
  27.         }finally { 
  28.             try { 
  29.                 inputStream.close(); 
  30.             } catch (IOException e) { 
  31.                 e.printStackTrace(); 
  32.             } 
  33.             sqlSession.close(); 
  34.         } 
  35.     } 
  36.  

輸出結(jié)果:

  1. User{id=1, name='tian', age=22} 

整體步驟:

 

另外一種啟動方式

  1. import com.tian.mybatis.entity.User
  2. import org.apache.ibatis.builder.xml.XMLConfigBuilder; 
  3. import org.apache.ibatis.io.Resources; 
  4. import org.apache.ibatis.session.Configuration; 
  5. import org.apache.ibatis.session.SqlSession; 
  6. import org.apache.ibatis.session.SqlSessionFactory; 
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  8. import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory; 
  9.  
  10. import java.io.IOException; 
  11. import java.io.InputStream; 
  12. import java.util.Properties; 
  13.  
  14. public class MybatisApplication { 
  15.  
  16.     public static void main(String[] args) { 
  17.         String resource = "mybatis-config.xml"
  18.         InputStream inputStream = null
  19.         try { 
  20.             inputStream = Resources.getResourceAsStream(resource); 
  21.         } catch (IOException e) { 
  22.             e.printStackTrace(); 
  23.         } 
  24.         //解析xml文件 
  25.         XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, nullnull); 
  26.         //構(gòu)建一個SqlSessionFactory工廠類 
  27.         SqlSessionFactory sqlSessionFactory = build(parser.parse()); 
  28.         //創(chuàng)建一個SqlSession 
  29.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  30.         //獲取數(shù)據(jù)并解析成User對象 
  31.         User user = sqlSession.selectOne("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); 
  32.         System.out.println(user); 
  33.     } 
  34.  
  35.     public static SqlSessionFactory build(Configuration config) { 
  36.         return new DefaultSqlSessionFactory(config); 
  37.     } 

輸出和上面一樣。還可以直接使用Java代碼而不用mybatis-config.xml。

  1. //創(chuàng)建數(shù)據(jù)源 
  2. DataSource dataSource = getDataSource(); 
  3.  
  4. TransactionFactory transactionFactory = new JdbcTransactionFactory(); 
  5.  
  6. Environment environment = new Environment("development", transactionFactory, dataSource); 
  7.  
  8. Configuration configuration = new Configuration(environment); 
  9. configuration.addMapper(BlogMapper.class); 
  10.  
  11. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); 

小總結(jié)

從上面這個案例中我們大致能猜到,Mybatis中最主要幾個組件:

SqlSessionFactoryBuilder

SqlSessionFactory

SqlSession

Mapper

SqlSessionFactoryBuilder這個類可以被初始、使用和丟棄,如果你已經(jīng)創(chuàng)建好了一個 SqlSessionFactory后就不用再保留它。因此 ,SqlSessionFactoryBuilder 的最好作用域是方法體內(nèi),比如說定義一個方法變量。

你可以重復(fù)使用SqlSessionFactoryBuilder 生成多個 SqlSessionFactory 實例,但是最好不要強(qiáng)行保留,因為 XML 的解析資源要用來做其它更重要的事。

SqlSessionFactory一旦創(chuàng)建,SqlSessionFactory就會在整個應(yīng)用過程中始終存在。所以沒有理由去銷毀和再創(chuàng)建它,一個 應(yīng)用運(yùn)行中也不建議多次創(chuàng)建 SqlSessionFactory。如果真的那樣做,會顯得很拙劣。

因此 SqlSessionFactory最好的作用域是 Application??梢杂卸喾N方法實現(xiàn)。最簡單的方法是單例模式或者是靜態(tài)單例模式。然而這既不是廣泛贊成和好用的。反而,使用 Google Guice 或 Spring 來進(jìn)行依賴反射會更好。這些框架允 許你生成管理器來管理 SqlSessionFactory的單例生命周期

SqlSession每個線程都有自己的 SqlSession 實例,SqlSession 實例是不能被共享,也是不是線程安全的。因此最好 使用 Request 作用域或者方法體作用域。

不要使用類的靜態(tài)變量來引用一個 SqlSession 實例,甚至不要使用類的一個實例變更來引用。永遠(yuǎn)不要在一個被管理域中引用 SqlSession,比如說在 Servlet 中的HttpSession 中。如果你正在使用 WEB 框架,應(yīng)該讓 SqlSession 跟隨 HTTP 請求的相似作用域。

也就是說,在收到一個 HTTP 請求過后,打開 SqlSession,等返回一個回應(yīng)以后,立馬關(guān)掉這個 SqlSession。關(guān)閉 SqlSession 是非常重要的。你必須要確保 SqlSession 在 finally 方法體中正常關(guān)閉。

  1. SqlSession session = sqlSessionFactory.openSession(); 
  2. try { 
  3. // do work 
  4. } finally { 
  5. session.close(); 

使用這種模式來貫穿你的所有代碼,以確保所有數(shù)據(jù)庫資源都被完全關(guān)閉。

Mapper

Mapper 是一種你創(chuàng)建的用于綁定映射語句的接口。Mapper 接口的實例是用 SqlSession 來獲得的。同樣 , 從技術(shù)上來說,最廣泛的 Mapper 實例作用域像 SqlSession 一樣,使用請求作用域。確切地說,在方法 被調(diào)用的時候調(diào)用 Mapper 實例,然后使用后,就自動銷毀掉。不需要使用明確的注銷。當(dāng)一個請求執(zhí) 行正確無誤的時候,像 SqlSession 一樣,你可以輕而易舉地操控這一切。保持簡單性,保持 Mapper 在 方法體作用域內(nèi)。

  1. //獲取數(shù)據(jù)并解析成User對象 
  2. User user = sqlSession.selectOne("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); 
  3. System.out.println(user); 

這里映射涉及到四個主體:

  1. 實體類User。
  2. 接口UaerMapper。
  3. xml配置文件UserMapper。
  4. 數(shù)據(jù)庫表m_user

Mybatis的五部曲:

 

總結(jié)

 

回顧JDBC的demo,JDBC中的問題,創(chuàng)建一個Mybatis示例,總結(jié)出重要的四個組件,以及每個組件的作用。

本文轉(zhuǎn)載自微信公眾號「Java后端技術(shù)全?!?,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Java后端技術(shù)全棧公眾號。

 

責(zé)任編輯:武曉燕 來源: Java后端技術(shù)全棧
相關(guān)推薦

2021-09-30 07:59:06

zookeeper一致性算法CAP

2019-08-16 09:41:56

UDP協(xié)議TCP

2021-01-15 12:56:36

人工智能人工智能應(yīng)用

2021-05-07 07:52:51

Java并發(fā)編程

2022-03-29 08:23:56

項目數(shù)據(jù)SIEM

2023-09-25 08:32:03

Redis數(shù)據(jù)結(jié)構(gòu)

2023-11-07 07:46:02

GatewayKubernetes

2023-10-04 00:32:01

數(shù)據(jù)結(jié)構(gòu)Redis

2021-09-10 13:06:45

HDFS底層Hadoop

2021-07-28 13:29:57

大數(shù)據(jù)PandasCSV

2024-08-27 11:00:56

單例池緩存bean

2017-03-30 22:41:55

虛擬化操作系統(tǒng)軟件

2025-02-14 08:53:24

2023-11-22 07:54:33

Xargs命令Linux

2021-12-13 10:43:45

HashMapJava集合容器

2021-10-21 06:52:17

ZooKeeper分布式配置

2023-12-07 09:07:58

2018-09-26 11:02:46

微服務(wù)架構(gòu)組件

2021-04-11 08:30:40

VRAR虛擬現(xiàn)實技術(shù)

2021-11-10 07:47:48

Traefik邊緣網(wǎng)關(guān)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號