01.mybatis使用引導與准備
1.ssm框架
指: sping+springMVC+mybatis
2.學習mybatis前准備web標准項目結構
model中的Ticket代碼如下:

1 package com.day01.ssm.mybatisDemo.model; 2 3 /** 4 * 課程筆記:http://www.cnblogs.com/newAndHui/category/1153640.html 5 * 疑問咨詢wx:851298348 6 */ 7 public class Ticket { 8 private Integer id; 9 private String startStation; 10 private String stopStation; 11 private String startTime; 12 private Integer ticketPrice; 13 14 public Integer getId() { 15 return id; 16 } 17 18 public void setId(Integer id) { 19 this.id = id; 20 } 21 22 public String getStartStation() { 23 return startStation; 24 } 25 26 public void setStartStation(String startStation) { 27 this.startStation = startStation; 28 } 29 30 public String getStopStation() { 31 return stopStation; 32 } 33 34 public void setStopStation(String stopStation) { 35 this.stopStation = stopStation; 36 } 37 38 public String getStartTime() { 39 return startTime; 40 } 41 42 public void setStartTime(String startTime) { 43 this.startTime = startTime; 44 } 45 46 public Integer getTicketPrice() { 47 return ticketPrice; 48 } 49 50 public void setTicketPrice(Integer ticketPrice) { 51 this.ticketPrice = ticketPrice; 52 } 53 }
dao層接口代碼:

1 package com.day01.ssm.mybatisDemo.dao; 2 3 import com.day01.ssm.mybatisDemo.model.Ticket; 4 5 import java.util.List; 6 7 /** 8 * 課程筆記:http://www.cnblogs.com/newAndHui/category/1153640.html 9 * 疑問咨詢wx:851298348 10 */ 11 public interface ITicketDao { 12 //增加 13 public void save(Ticket ticket); 14 //刪除 15 public void deleteById(Integer id); 16 //修改 17 public void update(Ticket ticket); 18 //查找單個 19 public Ticket queryById(Integer id); 20 //查找所有 21 public List<Ticket> queryAll(); 22 }
dao實現代碼結構

1 package com.day01.ssm.mybatisDemo.dao.impl; 2 3 import com.day01.ssm.mybatisDemo.dao.ITicketDao; 4 import com.day01.ssm.mybatisDemo.model.Ticket; 5 6 import java.util.List; 7 8 /** 9 * 課程筆記:http://www.cnblogs.com/newAndHui/category/1153640.html 10 * 疑問咨詢wx:851298348 11 */ 12 13 /** 14 * 使用mybatis完成CRUD 15 */ 16 public class TicketDao implements ITicketDao { 17 @Override 18 public void save(Ticket ticket) { 19 //以前 加 鏈 預 執 釋 20 //現在 mybatis 21 22 } 23 24 @Override 25 public void deleteById(Integer id) { 26 27 } 28 29 @Override 30 public void update(Ticket ticket) { 31 32 } 33 34 @Override 35 public Ticket queryById(Integer id) { 36 return null; 37 } 38 39 @Override 40 public List<Ticket> queryAll() { 41 return null; 42 } 43 }
到此准備工作完成.
02.03.04.05.mybatis實現增刪改查
項目結構圖先看為快:
1.框架和最佳實踐
框架(Framework):
什么是框架,框架從何而來,為什么使用框架?
框架:
1.是一系列jar包,其本質是對JDK功能的拓展.
2.框架是一組程序的集合,包含了一系列的最佳實踐,作用是解決某一個領域的問題.
不同框架的目的就是解決不同領域的問題.
最佳實踐(Best Practice):實際上是無數程序員經歷過無數次嘗試之后,總結出來的處理特定問題的特定方法.
如果把程序員的自由發揮看作是一條通往成功的途徑,最佳實踐就是其中的最短路徑,能極大的解放生產力.
最佳實踐三要素:可讀性,可維護性,可拓展性.
消除重復
化繁為簡
簡單必須可讀,簡單必須可拓展
減少依賴,消除耦合
Web開發中的最佳實踐:分層開發模式,即分工合作
JavaEE開發根據職責的縱向划分:表現層,業務層,持久層:
表現層(Predentation Layer):web/mvc:負責處理與界面交互的相關操作 (Struts2/Spring MVC)
業務層(Business Layer):service: 負責復雜的業務邏輯計算和判斷 (Spring)
持久層(Persistent Layer):dao: 負責將業務邏輯數據進行持久化存儲 (Hibernate/MyBatis)
2.ORM 與 MyBatis
對象關系映射(Object Relational Mapping,簡稱ORM/OR Mapping):
是一種為了解決面向對象與關系數據庫存在的互不匹配的現象的技術。
簡單的說,ORM是通過使用描述對象和數據庫之間映射的元數據,將java程序中的對象自動持久化到關系數據庫中。
避免直接使用SQL語句對關系型數據庫中的數據進行操作.
減少代碼編寫量,提高產品質量.
ORM 主要解決對象-關系的映射:
面向對象概念 面向關系概念
類 表
對象 表的行(記錄)
屬性 表的列(字段)
ORM的實現思想:
將關系數據庫中表中的記錄映射成為對象,以對象的形式展現,程序員可以把對數據庫的操作轉化為對對象的操作。
因此ORM的目的是為了方便開發人員以面向對象的思想來實現對數據庫的操作。
ORM 采用元數據來描述對象-關系映射細節:
元數據通常采用 XML 格式,並且存放在專門的對象-關系映射文件中。
目前流行的ORM框架:
1.JPA:本身是一種ORM規范,不是ORM框架.由各大ORM框架提供實現.
2.Hibernate:目前最流行的ORM框架.設計靈巧,性能優秀,文檔豐富.
3.MyBatis:本是apache的一個開源項目iBatis,提供的持久層框架包括SQL Maps和DAO,允許開發人員直接編寫SQL.
等
3.MyBatis歷史
MyBatis前世今生:
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名為MyBatis ,2013年11月遷移到Github。
iBATIS一詞來源於“internet”和“abatis”的組合,是一個基於Java的持久層框架。
iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO.
==================================================================================
MyBatis的優勢:
MyBatis 是支持普通 SQL查詢,存儲過程和高級映射的優秀持久層框架。
MyBatis 消除了幾乎所有的JDBC代碼和參數的手工設置以及結果集的檢索。
MyBatis 使用簡單的XML或注解用於配置和映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。
4.MyBatis完成CRUD步驟
1.使用框架第一步:拷貝jar包.
a:MySQL驅動:mysql-connector-java-5.1.22-bin.jar
b:MyBatis的核心jar:mybatis-3.2.1.jar
c:MyBatis的依賴jar:MyBatis目錄\lib中所有jar.
ps:commons-logging-1.1.1.jar其實可以不需要
2.MyBatis的主配置文件:
MyBatis-config.xml--->從PDF中去找.
3.映射文件(寫sql語句的文件)
4.創建鏈接
備注:
操作步驟:
無論是用過的Hibernate,MyBatis通用的操作步驟:
1. 從配置文件(通常是XML配置文件中)得到 sqlsessionfactory(相當於DataSource)。
2. 由sqlSessionfactory 產生 sqlSession(相當於Connection)。
3. 在session 中完成對數據的增刪改查和事務提交等。
4. 在用完之后關閉session 。
具體實現步驟:
1.jar包
2. 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 <!--作用:配置鏈接數據庫相關的信息--> 5 <configuration> 6 <!-- 環境配置--> 7 <environments default="development"> 8 <!--具體的數據庫配置--> 9 <environment id="development"> 10 <!-- 事務管理--> 11 <transactionManager type="JDBC"/> 12 <!--dataSource連接池--> 13 <dataSource type="POOLED"> 14 <property name="driver" value="com.mysql.jdbc.Driver"/> 15 <property name="url" value="jdbc:mysql://localhost:3306/station_data"/> 16 <property name="username" value="root"/> 17 <property name="password" value="admin"/> 18 </dataSource> 19 </environment> 20 </environments> 21 22 <mappers> 23 <!--映射文件 關聯sql 語句的文件--> 24 <mapper resource="mapper/ticketMapper.xml"/> 25 </mappers> 26 </configuration>
主配置文件模板來源於中文官方文檔第5頁.
3.映射文件(寫sql語句的文件)

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 <!-- 5 namespace:該映射文件的名字,理論上可以任意取 6 --> 7 <mapper namespace="org.mybatis.example.BlogMapper"> 8 <select id="yy" parameterType="int" resultType="com.day01.ssm.mybatisDemo.model.Ticket"> 9 SELECT id,start_station startStation,stop_station stopStation,start_time startTime,ticket_price ticketPrice FROM ticket WHERE id=#{id} 10 </select> 11 12 <insert id="tt" parameterType="com.day01.ssm.mybatisDemo.model.Ticket" > 13 INSERT INTO ticket (start_station,stop_station) VALUES (#{startStation},#{stopStation}) 14 </insert> 15 16 <delete id="dd" parameterType="int"> 17 DELETE FROM ticket WHERE id=#{id} 18 </delete> 19 20 <update id="uu" parameterType="com.day01.ssm.mybatisDemo.model.Ticket"> 21 UPDATE ticket SET start_station=#{startStation},stop_station=#{stopStation} WHERE id=#{id} 22 </update> 23 24 <select id="ss" resultType="com.day01.ssm.mybatisDemo.model.Ticket"> 25 SELECT id,start_station startStation,stop_station stopStation,start_time startTime,ticket_price ticketPrice FROM ticket 26 27 </select> 28 </mapper>
該映射文件來源於中文官方文檔第7頁.
4.創建鏈接
CRUD具體實現代碼:

1 package com.day01.ssm.mybatisDemo.dao.impl; 2 3 import com.day01.ssm.mybatisDemo.dao.ITicketDao; 4 import com.day01.ssm.mybatisDemo.model.Ticket; 5 import org.apache.ibatis.io.Resources; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 10 import java.io.IOException; 11 import java.io.Reader; 12 import java.util.List; 13 14 /** 15 * 課程筆記:http://www.cnblogs.com/newAndHui/category/1153640.html 16 * 疑問咨詢wx:851298348 17 */ 18 19 /** 20 * 使用mybatis完成CRUD 21 */ 22 public class TicketDao implements ITicketDao { 23 @Override 24 public void save(Ticket ticket) { 25 //以前 加 鏈 預 執 釋 26 //現在 mybatis 27 try { 28 //指定mybatis主配置文件地址 29 String resource = "myBatis-config.xml"; 30 //讀取配置文件內容 31 Reader reader = Resources.getResourceAsReader(resource); 32 //從配置文件(通常是XML配置文件中)得到 sqlSessionfactory 33 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 34 // 由sqlSessionfactory 產生 sqlSession(相當於Connection)。 35 SqlSession sqlSession = sqlSessionFactory.openSession(); 36 //開啟事物 37 sqlSession.insert("org.mybatis.example.BlogMapper.tt",ticket); 38 //提交事物 39 sqlSession.commit(); 40 sqlSession.close(); 41 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 46 47 } 48 49 @Override 50 public void deleteById(Integer id) { 51 //以前 加 鏈 預 執 釋 52 //現在 mybatis 53 try { 54 //指定mybatis主配置文件地址 55 String resource = "myBatis-config.xml"; 56 //讀取配置文件內容 57 Reader reader = Resources.getResourceAsReader(resource); 58 //從配置文件(通常是XML配置文件中)得到 sqlSessionfactory 59 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 60 // 由sqlSessionfactory 產生 sqlSession(相當於Connection)。 61 SqlSession sqlSession = sqlSessionFactory.openSession(); 62 //開啟事物 63 sqlSession.delete("org.mybatis.example.BlogMapper.dd",id); 64 //提交事物 65 sqlSession.commit(); 66 sqlSession.close(); 67 68 } catch (IOException e) { 69 e.printStackTrace(); 70 } 71 72 } 73 74 @Override 75 public void update(Ticket ticket) { 76 77 //以前 加 鏈 預 執 釋 78 //現在 mybatis 79 try { 80 //指定mybatis主配置文件地址 81 String resource = "myBatis-config.xml"; 82 //讀取配置文件內容 83 Reader reader = Resources.getResourceAsReader(resource); 84 //從配置文件(通常是XML配置文件中)得到 sqlSessionfactory 85 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 86 // 由sqlSessionfactory 產生 sqlSession(相當於Connection)。 87 SqlSession sqlSession = sqlSessionFactory.openSession(); 88 89 sqlSession.update("org.mybatis.example.BlogMapper.uu",ticket); 90 //提交事物 91 sqlSession.commit(); 92 sqlSession.close(); 93 94 } catch (IOException e) { 95 e.printStackTrace(); 96 } 97 } 98 99 @Override 100 public Ticket queryById(Integer id) { 101 try { 102 //指定mybatis主配置文件地址 103 String resource = "myBatis-config.xml"; 104 //讀取配置文件內容 105 Reader reader = Resources.getResourceAsReader(resource); 106 //從配置文件(通常是XML配置文件中)得到 sqlSessionfactory 107 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 108 // 由sqlSessionfactory 產生 sqlSession(相當於Connection)。 109 SqlSession sqlSession = sqlSessionFactory.openSession(); 110 //sqlSession 中完成對數據的增刪改查和事務提交等 111 Ticket ticket= (Ticket)sqlSession.selectOne("org.mybatis.example.BlogMapper.yy", id); 112 sqlSession.close(); 113 return ticket; 114 } catch (IOException e) { 115 e.printStackTrace(); 116 } 117 return null; 118 } 119 120 @Override 121 public List<Ticket> queryAll() { 122 123 try { 124 //指定mybatis主配置文件地址 125 String resource = "myBatis-config.xml"; 126 //讀取配置文件內容 127 Reader reader = Resources.getResourceAsReader(resource); 128 //從配置文件(通常是XML配置文件中)得到 sqlSessionfactory 129 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 130 // 由sqlSessionfactory 產生 sqlSession(相當於Connection)。 131 SqlSession sqlSession = sqlSessionFactory.openSession(); 132 //sqlSession 中完成對數據的增刪改查和事務提交等 133 List<Ticket> list = sqlSession.selectList("org.mybatis.example.BlogMapper.ss"); 134 sqlSession.close(); 135 return list; 136 } catch (IOException e) { 137 e.printStackTrace(); 138 } 139 return null; 140 141 142 } 143 }
測試代碼:

1 package com.day01.ssm.mybatisDemo.testDao; 2 3 import com.day01.ssm.mybatisDemo.dao.impl.TicketDao; 4 import com.day01.ssm.mybatisDemo.model.Ticket; 5 import org.junit.Test; 6 7 import java.util.List; 8 9 /** 10 * 課程筆記:http://www.cnblogs.com/newAndHui/category/1153640.html 11 * 疑問咨詢wx:851298348 12 */ 13 public class TestTicketDao { 14 private TicketDao ticketDao=new TicketDao(); 15 /** 16 * 17 */ 18 @Test 19 public void testQueryById(){ 20 Ticket ticket = ticketDao.queryById(2); 21 System.out.println("ticket="+ticket); 22 } 23 24 @Test 25 public void testSave(){ 26 Ticket ticket = new Ticket(); 27 ticket.setStartStation("上海"); 28 ticket.setStopStation("北京"); 29 ticketDao.save(ticket); 30 } 31 32 /** 33 * 測試刪除 34 */ 35 @Test 36 public void testDelete(){ 37 ticketDao.deleteById(6); 38 39 } 40 41 /** 42 * 更新車票 43 */ 44 @Test 45 public void testUpdate(){ 46 Ticket ticket = new Ticket(); 47 ticket.setId(2); 48 ticket.setStartStation("北京-改"); 49 ticket.setStopStation("成都"); 50 51 ticketDao.update(ticket); 52 } 53 @Test 54 public void test(){ 55 List<Ticket> tickets = ticketDao.queryAll(); 56 System.out.println(" tickets= "+tickets); 57 58 } 59 }