自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

老師又問我 MyBatis 了

開發(fā) 前端
MyBatis(前身是iBatis)是一個支持普通SQL查詢、存儲過程以及高級映射的持久層框架。

[[433479]]

GitHub:https://github.com/nateshao/ssm/tree/master/112-mybatis-hello

1. 什么是MyBatis

什么是MyBatis?

“MyBatis(前身是iBatis)是一個支持普通SQL查詢、存儲過程以及高級映射的持久層框架。

“MyBatis框架也被稱之為ORM(Object/Relation Mapping,即對象關系映射)框架。所謂的ORM就是一種為了解決面向對象與關系型數(shù)據(jù)庫中數(shù)據(jù)類型不匹配的技術,它通過描述Java對象與數(shù)據(jù)庫表之間的映射關系,自動將Java應用程序中的對象持久化到關系型數(shù)據(jù)庫的表中。

ORM框架的工作原理

Hibernate與MyBatis有什么區(qū)別?

Hibernate

  • Hibernate是一個全表映射的框架。
  • 通常開發(fā)者只需定義好持久化對象到數(shù)據(jù)庫表的映射關系,就可以通過Hibernate提供的方法完成持久層操作。
  • 開發(fā)者并不需要熟練的掌握SQL語句的編寫,Hibernate會根據(jù)制定的存儲邏輯,自動的生成對應的SQL,并調用JDBC接口來執(zhí)行,所以其開發(fā)效率會高于MyBatis。
  • Hibernate也存在一些缺點,例如它在多表關聯(lián)時,對SQL查詢的支持較差;更新數(shù)據(jù)時,需要發(fā)送所有字段;不支持存儲過程;不能通過優(yōu)化SQL來優(yōu)化性能等。

MyBatis

MyBatis是一個半自動映射的框架。

“半自動”是相對于Hibernate全表映射而言的,MyBatis需要手動匹配提供POJO、SQL和映射關系,而Hibernate只需提供POJO和映射關系即可。

與Hibernate相比,雖然使用MyBatis手動編寫SQL要比使用Hibernate的工作量大,但MyBatis可以配置動態(tài)SQL并優(yōu)化SQL,可以通過配置決定SQL的映射規(guī)則,它還支持存儲過程等。對于一些復雜的和需要優(yōu)化性能的項目來說,顯然使用MyBatis更加合適。

2. MyBatis的下載和使用

下載地址:https://github.com/mybatis/mybatis-3/releases

使用MyBatis框架非常簡單,只需在應用程序中引入MyBatis的核心包和lib目錄中的依賴包即可。

注意:如果底層采用的是MySQL數(shù)據(jù)庫,那么還需要將MySQL數(shù)據(jù)庫的驅動JAR包添加到應用程序的類路徑中;如果采用其他類型的數(shù)據(jù)庫,則同樣需要將對應類型的數(shù)據(jù)庫驅動包添加到應用程序的類路徑中。

3. MyBatis的工作原理

識記!!!

4. MyBatis入門程序

在實際開發(fā)中,查詢操作通常都會涉及到單條數(shù)據(jù)的精確查詢,以及多條數(shù)據(jù)的模糊查詢。

  • 根據(jù)客戶編號查詢客戶信息。
  • 根據(jù)客戶名模糊查詢客戶信息。

根據(jù)客戶編號查詢客戶信息

MySQL數(shù)據(jù)庫中,創(chuàng)建一個名為mybatis的數(shù)據(jù)庫,在此數(shù)據(jù)庫中創(chuàng)建一個t_customer表,同時預先插入幾條數(shù)據(jù)。

  1. /* 
  2.  Navicat MySQL Data Transfer 
  3.   
  4.  Source Server         : localhost_3306 
  5.  Source Server Version : 50717 
  6.  Source Host           : localhost:3306 
  7.  Source Database       : mybatis 
  8.   
  9.  Target Server Type    : MYSQL 
  10.  Target Server Version : 50717 
  11.  File Encoding         : 65001 
  12.   
  13.  Date: 2021-10-22 22:24:17 
  14.  */ 
  15.   
  16.  SET FOREIGN_KEY_CHECKS=0; 
  17.   
  18.  -- ---------------------------- 
  19.  -- Table structure for `t_customer` 
  20.  -- ---------------------------- 
  21.  DROP TABLE IF EXISTS `t_customer`; 
  22.  CREATE TABLE `t_customer` ( 
  23.    `id` int(32) NOT NULL AUTO_INCREMENT, 
  24.    `username` varchar(50) DEFAULT NULL
  25.    `jobs` varchar(50) DEFAULT NULL
  26.    `phone` varchar(16) DEFAULT NULL
  27.    PRIMARY KEY (`id`) 
  28.  ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; 
  29.   
  30.  -- ---------------------------- 
  31.  -- Records of t_customer 
  32.  -- ---------------------------- 
  33.  INSERT INTO `t_customer` VALUES ('1''aaa''dada''11111111'); 
  34.  INSERT INTO `t_customer` VALUES ('2''jack''teacher''13521210112'); 
  35.  INSERT INTO `t_customer` VALUES ('3''worker''worker''13311111234'); 
  36.  INSERT INTO `t_customer` VALUES ('4''zhangsan''maiyu''10086'); 
  37.  INSERT INTO `t_customer` VALUES ('5''zhangsan''manager''13233334444'); 
  38.  INSERT INTO `t_customer` VALUES ('6''zhangsan''manager''13233334444'); 

在IDEA中,創(chuàng)建一個名為112-mybatis-hello的maven項目,將MyBatis包、以及MySQL數(shù)據(jù)庫的驅動包一同添加到項目的pom.xml下, 并發(fā)布到類路徑中。

項目結構如下:

pom.xml

  1. <dependencies> 
  2.         <!-- mybatis核心包 --> 
  3.         <dependency> 
  4.             <groupId>org.mybatis</groupId> 
  5.             <artifactId>mybatis</artifactId> 
  6.             <version>3.5.1</version> 
  7.         </dependency> 
  8.         <!-- mysql驅動包 --> 
  9.         <dependency> 
  10.             <groupId>mysql</groupId> 
  11.             <artifactId>mysql-connector-java</artifactId> 
  12.             <version>5.1.47</version> 
  13.         </dependency> 
  14.         <!-- junit測試包 --> 
  15.         <dependency> 
  16.             <groupId>junit</groupId> 
  17.             <artifactId>junit</artifactId> 
  18.             <version>4.13.1</version> 
  19.             <scope>test</scope> 
  20.         </dependency> 
  21.         <dependency> 
  22.             <groupId>org.junit.jupiter</groupId> 
  23.             <artifactId>junit-jupiter-api</artifactId> 
  24.             <version>5.7.2</version> 
  25.         </dependency> 
  26.  
  27.     </dependencies> 

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-config.dtd"
  4. <configuration> 
  5.     <!--1.配置環(huán)境 ,默認的環(huán)境id為mysql--> 
  6.     <environments default="mysql"
  7.         <!--1.2.配置id為mysql的數(shù)據(jù)庫環(huán)境 --> 
  8.         <environment id="mysql"
  9.             <!-- 使用JDBC的事務管理 --> 
  10.             <transactionManager type="JDBC" /> 
  11.             <!--數(shù)據(jù)庫連接池 --> 
  12.             <dataSource type="POOLED"
  13.      <property name="driver" value="com.mysql.jdbc.Driver" /> 
  14.      <property name="url"  
  15.                             value="jdbc:mysql://localhost:3306/mybatis?useSSL=false" /> 
  16.      <property name="username" value="root" /> 
  17.      <property name="password" value="123456" /> 
  18.             </dataSource> 
  19.         </environment> 
  20.     </environments> 
  21.     <!--2.配置Mapper的位置 --> 
  22.     <mappers> 
  23.   <mapper resource="mapper/CustomerMapper.xml" /> 
  24.     </mappers> 
  25. </configuration> 

 log4j.properties

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-config.dtd"
  4. <configuration> 
  5.     <!--1.配置環(huán)境 ,默認的環(huán)境id為mysql--> 
  6.     <environments default="mysql"
  7.         <!--1.2.配置id為mysql的數(shù)據(jù)庫環(huán)境 --> 
  8.         <environment id="mysql"
  9.             <!-- 使用JDBC的事務管理 --> 
  10.             <transactionManager type="JDBC" /> 
  11.             <!--數(shù)據(jù)庫連接池 --> 
  12.             <dataSource type="POOLED"
  13.      <property name="driver" value="com.mysql.jdbc.Driver" /> 
  14.      <property name="url"  
  15.                             value="jdbc:mysql://localhost:3306/mybatis?useSSL=false" /> 
  16.      <property name="username" value="root" /> 
  17.      <property name="password" value="123456" /> 
  18.             </dataSource> 
  19.         </environment> 
  20.     </environments> 
  21.     <!--2.配置Mapper的位置 --> 
  22.     <mappers> 
  23.   <mapper resource="mapper/CustomerMapper.xml" /> 
  24.     </mappers> 
  25. </configuration> 

CustomerMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
  4. <!-- namespace表示命名空間 --> 
  5. <mapper namespace="com.nateshao.mapper.CustomerMapper"
  6.     <!--根據(jù)客戶編號獲取客戶信息 --> 
  7.  <select id="findCustomerById" parameterType="Integer" 
  8.   resultType="com.nateshao.po.Customer"
  9.   select * from t_customer where id = #{id} 
  10.  </select
  11.   
  12.  <!--根據(jù)客戶名模糊查詢客戶信息列表--> 
  13.  <select id="findCustomerByName" parameterType="String" 
  14.      resultType="com.nateshao.po.Customer"
  15.      <!-- select * from t_customer where username like '%${value}%' --> 
  16.      select * from t_customer where username like concat('%',#{value},'%'
  17.  </select
  18.   
  19.  <!-- 添加客戶信息 --> 
  20.  <insert id="addCustomer" parameterType="com.nateshao.po.Customer"
  21.      insert into t_customer(username,jobs,phone) 
  22.      values(#{username},#{jobs},#{phone}) 
  23.  </insert
  24.   
  25.  <!-- 更新客戶信息 --> 
  26.  <update id="updateCustomer" parameterType="com.nateshao.po.Customer"
  27.      update t_customer set 
  28.      username=#{username},jobs=#{jobs},phone=#{phone} 
  29.      where id=#{id} 
  30.  </update
  31.   
  32.  <!-- 刪除客戶信息 --> 
  33.  <delete id="deleteCustomer" parameterType="Integer"
  34.      delete from t_customer where id=#{id} 
  35.  </delete
  36. </mapper> 

 Customer.java

  1. package com.nateshao.po; 
  2.  
  3. /** 
  4.  * @date Created by 邵桐杰 on 2021/10/22 22:37 
  5.  * @微信公眾號 程序員千羽 
  6.  * @個人網站 www.nateshao.cn 
  7.  * @博客 https://nateshao.gitee.io 
  8.  * @GitHub https://github.com/nateshao 
  9.  * @Gitee https://gitee.com/nateshao 
  10.  * Description: 
  11.  */ 
  12. public class Customer { 
  13.     private Integer id; 
  14.     private String username; 
  15.     private String jobs; 
  16.     private String phone; 
  17.  
  18.     @Override 
  19.     public String toString() { 
  20.         return "Customer{" + 
  21.                 "id=" + id + 
  22.                 ", username='" + username + '\'' + 
  23.                 ", jobs='" + jobs + '\'' + 
  24.                 ", phone='" + phone + '\'' + 
  25.                 '}'
  26.     } 
  27.  
  28.     public Integer getId() { 
  29.         return id; 
  30.     } 
  31.  
  32.     public void setId(Integer id) { 
  33.         this.id = id; 
  34.     } 
  35.  
  36.     public String getUsername() { 
  37.         return username; 
  38.     } 
  39.  
  40.     public void setUsername(String username) { 
  41.         this.username = username; 
  42.     } 
  43.  
  44.     public String getJobs() { 
  45.         return jobs; 
  46.     } 
  47.  
  48.     public void setJobs(String jobs) { 
  49.         this.jobs = jobs; 
  50.     } 
  51.  
  52.     public String getPhone() { 
  53.         return phone; 
  54.     } 
  55.  
  56.     public void setPhone(String phone) { 
  57.         this.phone = phone; 
  58.     } 

MyBatisTest.java

  1. package com.nateshao.test; 
  2.  
  3. import com.nateshao.po.Customer; 
  4. import org.apache.ibatis.io.Resources; 
  5. import org.apache.ibatis.session.SqlSession; 
  6. import org.apache.ibatis.session.SqlSessionFactory; 
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  8. import org.junit.jupiter.api.Test; 
  9. import java.io.InputStream; 
  10. import java.util.List; 
  11.  
  12. /** 
  13.  * @date Created by 邵桐杰 on 2021/10/22 22:41 
  14.  * @微信公眾號 程序員千羽 
  15.  * @個人網站 www.nateshao.cn 
  16.  * @博客 https://nateshao.gitee.io 
  17.  * @GitHub https://github.com/nateshao 
  18.  * @Gitee https://gitee.com/nateshao 
  19.  * Description: Mybatis 測試 CRUD 
  20.  */ 
  21.  
  22. public class MybatisTest { 
  23.  
  24.     /** 
  25.      * 根據(jù)客戶編號查詢客戶信息 
  26.      * 
  27.      * @throws Exception 
  28.      */ 
  29.     @Test 
  30.     public void findCustomerByIdTest() throws Exception { 
  31.         // 1、讀取配置文件 
  32.         String resource = "mybatis-config.xml"
  33.         InputStream inputStream = 
  34.                 Resources.getResourceAsStream(resource); 
  35.         // 2、根據(jù)配置文件構建SqlSessionFactory 
  36.         SqlSessionFactory sqlSessionFactory = 
  37.                 new SqlSessionFactoryBuilder().build(inputStream); 
  38.         // 3、通過SqlSessionFactory創(chuàng)建SqlSession 
  39.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  40.         // 4、SqlSession執(zhí)行映射文件中定義的SQL,并返回映射結果 
  41.         Customer customer = sqlSession.selectOne("com.nateshao.mapper" 
  42.                 + ".CustomerMapper.findCustomerById", 1); 
  43.         // 打印輸出結果 
  44.         System.out.println(customer.toString()); 
  45.         // 5、關閉SqlSession 
  46.         sqlSession.close(); 
  47.     } 
  48.  
  49.     /** 
  50.      * 根據(jù)用戶名稱來模糊查詢用戶信息列表 
  51.      * 
  52.      * @throws Exception 
  53.      */ 
  54.     @Test 
  55.     public void findCustomerByNameTest() throws Exception { 
  56.         // 1、讀取配置文件 
  57.         String resource = "mybatis-config.xml"
  58.         InputStream inputStream = Resources.getResourceAsStream(resource); 
  59.         // 2、根據(jù)配置文件構建SqlSessionFactory 
  60.         SqlSessionFactory sqlSessionFactory = 
  61.                 new SqlSessionFactoryBuilder().build(inputStream); 
  62.         // 3、通過SqlSessionFactory創(chuàng)建SqlSession 
  63.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  64.         // 4、SqlSession執(zhí)行映射文件中定義的SQL,并返回映射結果 
  65.         List<Customer> customers = sqlSession.selectList("com.nateshao.mapper" 
  66.                 + ".CustomerMapper.findCustomerByName""j"); 
  67.         for (Customer customer : customers) { 
  68.             //打印輸出結果集 
  69.             System.out.println(customer); 
  70.         } 
  71.         // 5、關閉SqlSession 
  72.         sqlSession.close(); 
  73.     } 
  74.  
  75.     /** 
  76.      * 添加客戶 
  77.      * 
  78.      * @throws Exception 
  79.      */ 
  80.     @Test 
  81.     public void addCustomerTest() throws Exception { 
  82.         // 1、讀取配置文件 
  83.         String resource = "mybatis-config.xml"
  84.         InputStream inputStream = Resources.getResourceAsStream(resource); 
  85.         // 2、根據(jù)配置文件構建SqlSessionFactory 
  86.         SqlSessionFactory sqlSessionFactory = 
  87.                 new SqlSessionFactoryBuilder().build(inputStream); 
  88.         // 3、通過SqlSessionFactory創(chuàng)建SqlSession 
  89.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  90.         // 4、SqlSession執(zhí)行添加操作 
  91.         // 4.1創(chuàng)建Customer對象,并向對象中添加數(shù)據(jù) 
  92.         Customer customer = new Customer(); 
  93.         customer.setUsername("rose"); 
  94.         customer.setJobs("student"); 
  95.         customer.setPhone("13333533092"); 
  96.         // 4.2執(zhí)行SqlSession的插入方法,返回的是SQL語句影響的行數(shù) 
  97.         int rows = sqlSession.insert("com.nateshao.mapper" 
  98.                 + ".CustomerMapper.addCustomer", customer); 
  99.         // 4.3通過返回結果判斷插入操作是否執(zhí)行成功 
  100.         if (rows > 0) { 
  101.             System.out.println("您成功插入了" + rows + "條數(shù)據(jù)!"); 
  102.         } else { 
  103.             System.out.println("執(zhí)行插入操作失?。。?!"); 
  104.         } 
  105.         // 4.4提交事務 
  106.         sqlSession.commit(); 
  107.         // 5、關閉SqlSession 
  108.         sqlSession.close(); 
  109.     } 
  110.  
  111.     /** 
  112.      * 更新客戶 
  113.      * 
  114.      * @throws Exception 
  115.      */ 
  116.     @Test 
  117.     public void updateCustomerTest() throws Exception { 
  118.         // 1、讀取配置文件 
  119.         String resource = "mybatis-config.xml"
  120.         InputStream inputStream = Resources.getResourceAsStream(resource); 
  121.         // 2、根據(jù)配置文件構建SqlSessionFactory 
  122.         SqlSessionFactory sqlSessionFactory = 
  123.                 new SqlSessionFactoryBuilder().build(inputStream); 
  124.         // 3、通過SqlSessionFactory創(chuàng)建SqlSession 
  125.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  126.         // 4、SqlSession執(zhí)行更新操作 
  127.         // 4.1創(chuàng)建Customer對象,對對象中的數(shù)據(jù)進行模擬更新 
  128.         Customer customer = new Customer(); 
  129.         customer.setId(4); 
  130.         customer.setUsername("rose"); 
  131.         customer.setJobs("programmer"); 
  132.         customer.setPhone("13311111111"); 
  133.         // 4.2執(zhí)行SqlSession的更新方法,返回的是SQL語句影響的行數(shù) 
  134.         int rows = sqlSession.update("com.nateshao.mapper" 
  135.                 + ".CustomerMapper.updateCustomer", customer); 
  136.         // 4.3通過返回結果判斷更新操作是否執(zhí)行成功 
  137.         if (rows > 0) { 
  138.             System.out.println("您成功修改了" + rows + "條數(shù)據(jù)!"); 
  139.         } else { 
  140.             System.out.println("執(zhí)行修改操作失敗?。?!"); 
  141.         } 
  142.         // 4.4提交事務 
  143.         sqlSession.commit(); 
  144.         // 5、關閉SqlSession 
  145.         sqlSession.close(); 
  146.     } 
  147.  
  148.     /** 
  149.      * 刪除客戶 
  150.      * 
  151.      * @throws Exception 
  152.      */ 
  153.     @Test 
  154.     public void deleteCustomerTest() throws Exception { 
  155.         // 1、讀取配置文件 
  156.         String resource = "mybatis-config.xml"
  157.         InputStream inputStream = Resources.getResourceAsStream(resource); 
  158.         // 2、根據(jù)配置文件構建SqlSessionFactory 
  159.         SqlSessionFactory sqlSessionFactory = 
  160.                 new SqlSessionFactoryBuilder().build(inputStream); 
  161.         // 3、通過SqlSessionFactory創(chuàng)建SqlSession 
  162.         SqlSession sqlSession = sqlSessionFactory.openSession(); 
  163.         // 4、SqlSession執(zhí)行刪除操作 
  164.         // 4.1執(zhí)行SqlSession的刪除方法,返回的是SQL語句影響的行數(shù) 
  165.         int rows = sqlSession.delete("com.nateshao.mapper" 
  166.                 + ".CustomerMapper.deleteCustomer", 4); 
  167.         // 4.2通過返回結果判斷刪除操作是否執(zhí)行成功 
  168.         if (rows > 0) { 
  169.             System.out.println("您成功刪除了" + rows + "條數(shù)據(jù)!"); 
  170.         } else { 
  171.             System.out.println("執(zhí)行刪除操作失?。。?!"); 
  172.         } 
  173.         // 4.3提交事務 
  174.         sqlSession.commit(); 
  175.         // 5、關閉SqlSession 
  176.         sqlSession.close(); 
  177.     } 

總結

讀取配置文件

根據(jù)配置文件構建SqlSessionFactory

通過SqlSessionFactory創(chuàng)建SqlSession

使用SqlSession對象操作數(shù)據(jù)庫

關閉SqlSession

責任編輯:武曉燕 來源: 程序員千羽
相關推薦

2021-10-30 18:56:12

Spring工作框架

2023-07-18 19:11:21

配置信令系統(tǒng)

2021-09-09 18:12:22

內存分段式網絡

2020-12-11 09:24:19

Elasticsear存儲數(shù)據(jù)

2018-09-28 05:25:53

TopK算法代碼

2017-12-28 10:44:08

JavaScript瀏覽器網頁

2020-09-24 14:40:55

Python 開發(fā)編程語言

2018-10-28 22:37:00

計數(shù)排序排序面試

2018-11-01 13:49:23

桶排序排序面試

2020-04-22 11:19:07

貪心算法動態(tài)規(guī)劃

2014-07-23 10:19:02

小米4

2022-10-17 10:13:58

谷歌云游戲

2020-03-31 16:02:23

戴爾

2022-12-07 07:35:20

B站裁員隱情

2023-03-10 08:24:27

OOMdump線程

2023-10-30 22:23:12

Cacherkube版本

2021-07-22 07:50:47

刪庫系統(tǒng)數(shù)據(jù)

2019-05-27 08:09:43

WiFi無線信道上網

2021-01-22 10:09:23

簡歷求職者面試

2020-04-16 08:22:11

HTTPS加解密協(xié)議
點贊
收藏

51CTO技術棧公眾號