mybatis(1)mybatis入門程序

1、對原生態jdbc程序中問題總結

[java] view plain copy
  1. package com.xdy.mybatis.jdbc;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8.   
  9. public class JdbcTest {  
  10.   
  11.     public static void main(String[] args) {  
  12.         // 數據庫連接  
  13.         Connection connection = null;  
  14.         // 預編譯的Statement,使用預編譯的Statement提高數據庫性能  
  15.         PreparedStatement preparedStatement = null;  
  16.         // 結果 集  
  17.         ResultSet resultSet = null;  
  18.   
  19.         try {  
  20.             // 加載數據庫驅動  
  21.             Class.forName("com.mysql.jdbc.Driver");  
  22.   
  23.             // 通過驅動管理類獲取數據庫鏈接  
  24.             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",  
  25.                     "root""mysql");  
  26.             // 定義sql語句 ?表示佔位符  
  27.             String sql = "select * from user where username = ?";  
  28.             // 獲取預處理statement  
  29.             preparedStatement = connection.prepareStatement(sql);  
  30.             // 設置參數,第一個參數爲sql語句中參數的序號(從1開始),第二個參數爲設置的參數值  
  31.             preparedStatement.setString(1"王五");  
  32.             // 向數據庫發出sql執行查詢,查詢出結果集  
  33.             resultSet = preparedStatement.executeQuery();  
  34.             // 遍歷查詢結果集  
  35.             while (resultSet.next()) {  
  36.                 System.out.println(resultSet.getString("id") + "  " + resultSet.getString("username"));  
  37.             }  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             // 釋放資源  
  42.             if (resultSet != null) {  
  43.                 try {  
  44.                     resultSet.close();  
  45.                 } catch (SQLException e) {  
  46.                     // TODO Auto-generated catch block  
  47.                     e.printStackTrace();  
  48.                 }  
  49.             }  
  50.             if (preparedStatement != null) {  
  51.                 try {  
  52.                     preparedStatement.close();  
  53.                 } catch (SQLException e) {  
  54.                     // TODO Auto-generated catch block  
  55.                     e.printStackTrace();  
  56.                 }  
  57.             }  
  58.             if (connection != null) {  
  59.                 try {  
  60.                     connection.close();  
  61.                 } catch (SQLException e) {  
  62.                     // TODO Auto-generated catch block  
  63.                     e.printStackTrace();  
  64.                 }  
  65.             }  
  66.   
  67.         }  
  68.   
  69.     }  
  70.   
  71. }  

1.1 問題總結

 

1、數據庫連接,使用時就創建,不使用立即釋放,對數據庫進行頻繁連接開啓和關閉,造成數據庫資源浪費,影響 數據庫性能。

設想:使用數據庫連接池管理數據庫連接。

 

2、將sql語句硬編碼java代碼中,如果sql 語句修改,需要重新編譯java代碼,不利於系統維護。

設想:將sql語句配置在xml配置文件中,即使sql變化,不需要對java代碼進行重新編譯。

 

 

3、向preparedStatement中設置參數,對佔位符號位置和設置參數值,硬編碼在java代碼中,不利於系統維護。

設想:將sql語句及佔位符號和參數全部配置在xml中。

 

4、從resutSet中遍歷結果集數據時,存在硬編碼,將獲取表的字段進行硬編碼,,不利於系統維護。

設想:將查詢的結果集,自動映射成java對象。


2、入門程序


2.1 SqlMapConfig.xml

配置mybatis的運行環境,數據源、事務等。

[html] view plain copy
  1. <span style="font-size:14px;"><?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.     <!-- 和spring整合後 environments配置將廢除-->  
  7.     <environments default="development">  
  8.         <environment id="development">  
  9.         <!-- 使用jdbc事務管理,事務控制由mybatis-->  
  10.             <transactionManager type="JDBC" />  
  11.         <!-- 數據庫連接池,由mybatis管理-->  
  12.             <dataSource type="POOLED">  
  13.                 <property name="driver" value="com.mysql.jdbc.Driver" />  
  14.                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />  
  15.                 <property name="username" value="root" />  
  16.                 <property name="password" value="" />  
  17.             </dataSource>  
  18.         </environment>  
  19.     </environments>  
  20.       
  21. </configuration></span>  

2.2 根據用戶id(主鍵)查詢用戶信息

2.2.1 創建po

[java] view plain copy
  1. <span style="font-size:14px;">package com.xdy.mybatis.po;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.     private int id;  
  7.     private String username;  
  8.     private String sex;  
  9.     private Date birthday;  
  10.     private String address;  
  11.   
  12.     public int getId() {  
  13.         return id;  
  14.     }  
  15.   
  16.     public void setId(int id) {  
  17.         this.id = id;  
  18.     }  
  19.   
  20.     public String getUsername() {  
  21.         return username;  
  22.     }  
  23.   
  24.     public void setUsername(String username) {  
  25.         this.username = username;  
  26.     }  
  27.   
  28.     public String getSex() {  
  29.         return sex;  
  30.     }  
  31.   
  32.     public void setSex(String sex) {  
  33.         this.sex = sex;  
  34.     }  
  35.   
  36.     public Date getBirthday() {  
  37.         return birthday;  
  38.     }  
  39.   
  40.     public void setBirthday(Date birthday) {  
  41.         this.birthday = birthday;  
  42.     }  
  43.   
  44.     public String getAddress() {  
  45.         return address;  
  46.     }  
  47.   
  48.     public void setAddress(String address) {  
  49.         this.address = address;  
  50.     }  
  51.   
  52.     @Override  
  53.     public String toString() {  
  54.         return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="  
  55.                 + address + "]";  
  56.     }  
  57.   
  58.       
  59. }</span><span style="font-size:18px;">  
  60. </span>  

2.2.2 映射文件

[html] view plain copy
  1. <span style="font-size:14px;"><?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="test">  
  6.     <select id="findUserById" parameterType="int" resultType="com.xdy.mybatis.po.User">  
  7.         select * from user where id=#{value}  
  8.     </select>  
  9. </mapper></span>  

2.2.3 在SqlMapConfig.xml加載映射文件

[html] view plain copy
  1. <span style="font-size:14px;"><mappers>  
  2. <span style="white-space: pre;">  </span><mapper resource="sqlmap/User.xml"/>  
  3. </mappers></span>  

2.2.4 程序編寫

[java] view plain copy
  1. <span style="font-size:14px;">public class MybatisFirst {  
  2.   
  3.     @Test  
  4.     public void findUserByIdTest() throws IOException {  
  5.         // mybatis配置文件  
  6.         String resource = "SqlMapConfig.xml";  
  7.         // 得到配置文件流  
  8.         InputStream inputStream = Resources.getResourceAsStream(resource);  
  9.   
  10.         // 創建會話工廠,傳入mybatis的配置文件信息  
  11.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  12.   
  13.         // 通過工廠得到SqlSession  
  14.         SqlSession sqlSession = sqlSessionFactory.openSession();  
  15.   
  16.         // 通過SqlSession操作數據庫  
  17.         // 第一個參數:映射文件中statement的id,等於=namespace+"."+statement的id  
  18.         // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數  
  19.         // sqlSession.selectOne結果 是與映射文件中所匹配的resultType類型的對象  
  20.         // selectOne查詢出一條記錄  
  21.         User user = sqlSession.selectOne("test.findUserById"1);  
  22.   
  23.         System.out.println(user);  
  24.   
  25.         // 釋放資源  
  26.         sqlSession.close();  
  27.     }  
  28. }</span>  

2.3 根據用戶名稱模糊查詢用戶信息


使用User.xml,添加根據用戶名稱模糊查詢用戶信息的sql語句。

[html] view plain copy
  1. <select id="findUserByName" parameterType="java.lang.String" resultType="com.xdy.mybatis.po.User">  
  2.     select * from user where username like '%${value}%'  
  3. </select>  

2.3.1 程序代碼

[java] view plain copy
  1. @Test  
  2.     public void findUserByNameTest() throws IOException {  
  3.         // mybatis配置文件  
  4.         String resource = "SqlMapConfig.xml";  
  5.         // 得到配置文件流  
  6.         InputStream inputStream = Resources.getResourceAsStream(resource);  
  7.   
  8.         // 創建會話工廠,傳入mybatis的配置文件信息  
  9.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  10.   
  11.         // 通過工廠得到SqlSession  
  12.         SqlSession sqlSession = sqlSessionFactory.openSession();  
  13.   
  14.         // list中的user和映射文件中resultType所指定的類型一致  
  15.         List<User> list = sqlSession.selectList("test.findUserByName""小明");  
  16.   
  17.         System.out.println(list);  
  18.   
  19.         // 釋放資源  
  20.         sqlSession.close();  
  21.     }  

2.4 添加用戶

2.4.1 映射文件

在 User.xml中配置添加用戶的Statement

[html] view plain copy
  1. <insert id="insertUser" parameterType="com.xdy.mybatis.po.User">  
  2. <span style="white-space:pre">    </span>insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})  
  3. </insert>  

2.4.2 程序代碼

[java] view plain copy
  1. <span style="white-space:pre">    </span>@Test  
  2.     public void insertUserTest() throws IOException {  
  3.         // mybatis配置文件  
  4.         String resource = "SqlMapConfig.xml";  
  5.         // 得到配置文件流  
  6.         InputStream inputStream = Resources.getResourceAsStream(resource);  
  7.   
  8.         // 創建會話工廠,傳入mybatis的配置文件信息  
  9.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  10.   
  11.         // 通過工廠得到SqlSession  
  12.         SqlSession sqlSession = sqlSessionFactory.openSession();  
  13.           
  14.         //插入用戶對象  
  15.         User user = new User();  
  16.         user.setUsername("張三");  
  17.         user.setBirthday(new Date());  
  18.         user.setSex("1");  
  19.         user.setAddress("重慶");  
  20.   
  21.         sqlSession.insert("test.insertUser", user);  
  22.   
  23.         sqlSession.commit();  
  24.           
  25.         System.out.println(user.getId());  
  26.   
  27.         // 釋放資源  
  28.         sqlSession.close();  
  29.     }  

2.4.3 自增主鍵返回

mysql自增主鍵,執行insert提交之前自動生成一個自增主鍵。通過mysql函數獲取到剛插入記錄的自增主鍵:LAST_INSERT_ID(),是insert之後調用此函數。

 修改insertUser定義:

[html] view plain copy
  1. <insert id="insertUser" parameterType="com.xdy.mybatis.po.User">  
  2.     <selectKey keyProperty="id" order="AFTER" resultType="int">  
  3.         select last_insert_id()  
  4.     </selectKey>  
  5.     insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})  
  6. </insert>  

2.4.5 非自增主鍵返回(使用uuid())

使用mysqluuid()函數生成主鍵,需要修改表中id字段類型爲string,長度設置成35位。

執行思路:

先通過uuid()查詢到主鍵,將主鍵輸入 到sql語句中。

執行uuid()語句順序相對於insert語句之前執行。


通過oracle的序列生成主鍵:

[html] view plain copy
  1. <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">  
  2.     SELECT 序列名.nextval()  
  3. </selectKey>  

2.5 刪除用戶

2.5.1 映射文件

[html] view plain copy
  1. <delete id="deleteUser" parameterType="int">  
  2.     delete from user where id=#{id}  
  3. </delete>  

2.5.2 代碼

[java] view plain copy
  1. <span style="white-space:pre">    </span>@Test  
  2.     public void deleteUserTest() throws IOException {  
  3.         // mybatis配置文件  
  4.         String resource = "SqlMapConfig.xml";  
  5.         // 得到配置文件流  
  6.         InputStream inputStream = Resources.getResourceAsStream(resource);  
  7.         // 創建會話工廠,傳入mybatis的配置文件信息  
  8.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  9.         // 通過工廠得到SqlSession  
  10.         SqlSession sqlSession = sqlSessionFactory.openSession();  
  11.         sqlSession.delete("test.deleteUser"10);  
  12.         sqlSession.commit();  
  13.         // 釋放資源  
  14.         sqlSession.close();  
  15.     }  

2.6 更新用戶

2.6.1 映射文件

[html] view plain copy
  1. <update id="updateUser" parameterType="com.xdy.mybatis.po.User">  
  2.     update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}  
  3. </update>  

2.6.2 代碼

[java] view plain copy
  1. <span style="font-size:12px;"><span style="white-space: pre;">  </span>@Test  
  2.     public void updateUserTest() throws IOException {  
  3.         // mybatis配置文件  
  4.         String resource = "SqlMapConfig.xml";  
  5.         // 得到配置文件流  
  6.         InputStream inputStream = Resources.getResourceAsStream(resource);  
  7.         // 創建會話工廠,傳入mybatis的配置文件信息  
  8.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  9.         // 通過工廠得到SqlSession  
  10.         SqlSession sqlSession = sqlSessionFactory.openSession();  
  11.         User user = new User();  
  12.         user.setId(16);  
  13.         user.setUsername("張小凡");  
  14.         user.setBirthday(new Date());  
  15.         user.setSex("1");  
  16.         user.setAddress("重慶市江北區");  
  17.         sqlSession.update("test.updateUser", user);  
  18.         sqlSession.commit();  
  19.         // 釋放資源  
  20.         sqlSession.close();  
  21.     }</span>  

2.7 總結

 

2.7.1 parameterType

在映射文件中通過parameterType指定輸入 參數的類型。

2.7.2 resultType

在映射文件中通過resultType指定輸出結果的類型。

 

2.7.3 #{}${}

 

#{}表示一個佔位符號,#{}接收輸入參數,類型可以是簡單類型,pojohashmap

如果接收簡單類型,#{}中可以寫成value或其它名稱。

#{}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。

 

${}表示一個拼接符號,會引用sql注入,所以不建議使用${}

${}接收輸入參數,類型可以是簡單類型,pojohashmap

如果接收簡單類型,${}中只能寫成value

${}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。

2.7.4 selectOneselectList

selectOne表示查詢出一條記錄進行映射。如果使用selectOne可以實現使用selectList也可以實現(list中只有一個對象)。

selectList表示查詢出一個列表(多條記錄)進行映射。如果使用selectList查詢多條記錄,不能使用selectOne

如果使用selectOne報錯:

org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4

2.8 mybatishibernate本質區別和應用場景

 

hibernate:是一個標準ORM框架(對象關係映射)。入門門檻較高的,不需要程序寫sqlsql語句自動生成了。

sql語句進行優化、修改比較困難的。

應用場景:

適用與需求變化不多的中小型項目,比如:後臺管理系統,erpormoa。。

 

mybatis:專注是sql本身,需要程序員自己編寫sql語句,sql修改、優化比較方便。mybatis是一個不完全 的ORM框架,雖然程序員自己寫sqlmybatis 也可以實現映射(輸入映射、輸出映射)。

應用場景:

適用與需求變化較多的項目,比如:互聯網項目。

企業進行技術選型,以低成本 高回報作爲技術選型的原則,根據項目組的技術力量進行選擇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章