Mybatis框架學習1:入門

#框架介紹 ##Mybatis介紹 ​ MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis。是一個基於Java的持久層框架。 ​ Mybatis本質和Hibernate等持久層框架同樣,底層均是基於jdbc的,做用均是實現數據的持久化。 ##Mybatis和Hibernate對比 | 對比項 | Mybatis | Hibernate | | :------: | :--------------------------------: | :--------------------------------------: | | 底層原理 | 基於jdbc | 基於jdbc | | 開發速度 | 業務無複雜查詢時較快,上手快 | 複雜查詢語句多時較快。上手慢 | | sql優化 | 複雜 | 手寫sql,容易優化 | | 緩存 | 支持一級、二級緩存,支持第三方緩存 | 支持一級、更好的二級緩存,支持第三方緩存 | | 可移植性 | 不一樣數據庫需寫不一樣sql語句 | Hibernate負責映射 | | 日誌系統 | 具備本身的日誌系統 | 使用第三方日誌工具 | #準備工做 ##建立數據java

CREATE TABLE `user` (
  `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `description` text
) ;
INSERT INTO `user` VALUES ('1', 'uzi', 'a gun');
INSERT INTO `user` VALUES ('2', 'the Shy', 'ChampionTop');
INSERT INTO `user` VALUES ('3', 'rookie', 'ChampionMid');
INSERT INTO `user` VALUES ('4', 'clearlove', 'old man');

##資源準備 若是建立的是java項目,那麼須要下載如下jar包:mysql

  • mybatis-3.4.6.jarsql

  • commons-logging-1.2.jar數據庫

  • log4j-1.2.17.jarapache

  • asm-5.2.jar緩存

  • cglib-3.2.5.jarsession

    若是建立的是maven項目,則導入對應依賴便可。mybatis

#建立項目app

我這裏建立的是java項目 ##導入jar包框架

在項目根目錄下建立一個文件夾,命名爲lib,將下載好的jar包複製進去後,郵件選中,選擇 Buildpath—>add to BuildPath。

a

##建立Mybatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--須要導入mybatis的dtd約束文件 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--
              屬性 
        <properties></properties>
             全局參數設置
        <settings></settings>
             類型別名
        <typeAliases></typeAliases>
            類型處理器
        <typeHandles></typeHandles>
            對象工廠
        <objectFactory></objectFactory>
            插件
        <plugins></plugins>
        以上屬性現階段均可以忽視,後面會詳細介紹
    -->
    

<!-- 配置mybatis的環境信息 -->

<environments default="development">
    <environment id="development">
        <!-- 配置JDBC事務控制,由mybatis進行管理 -->
        <transactionManager type="JDBC"></transactionManager>
        <!-- 配置數據源,採用dbcp鏈接池 -->
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
    <!-- 使用mappers標籤加載sql映射文件 -->    
<mappers>
    <!-- 此處根據本身實際的sql映射文件位置來填寫-->
    <mapper resource="com/mybatis/mapping/User.xml"/>
</mappers>
</configuration>

##建立實體類

package com.mybatis.domain;
  
  public class User {
  	private int id;
  	private String name;
  	private String description;
  	public int getId() {
  		return id;
  	}
  	public void setId(int id) {
  		this.id = id;
  	}
  	public String getName() {
  		return name;
  	}
  	public void setName(String name) {
  		this.name = name;
  	}
  	public String getDescription() {
  		return description;
  	}
  	public void setDescription(String description) {
  		this.description= description;
  	}
  	@Override
  	public String toString() {
  		return "User [id=" + id + ", name=" + name + ", description=" + description+ "]";
  	}
  }

##建立sql映射配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper    
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:命名空間,對sql進行一個分類管理 -->
<!-- 注意:namespace在mapper代理時,具備重要且特殊的做用 -->
<mapper namespace="com.mybatis.mapping.userMapper">
         <!-- 
 2             使用id進行查詢
 3         查詢,使用select來表示一個查詢的statement,至關於statement.executeQuery
 4         id:表示該statement惟一標識
 5         parameterType:輸入參數類型
 6         resultType:輸出參數類型,使用的是User類,則會將查詢出來的記錄封裝到該類中
 7         #{id}:使用#{}接收輸入的參數,其中的"id"屬性名任意,能夠爲uid,也能夠爲別的。
 8       -->
 	  <!-- 查詢 -->
      <select id="getUser" parameterType="int" resultType="com.mybatis.domain.User">
         SELECT * FROM user WHERE id= #{id}
	   </select>
	   <!-- 插入 -->
	   <insert id="addUser" parameterType="com.mybatis.domain.User">
	   	INSERT INTO user(name,description) VALUES(#{name},#{description})
	   </insert>
	   <!--刪除-->
	   <delete id="deleteUser" parameterType="int">
	   DELETE FROM user WHERE id= #{id}
	   </delete>
	   <!-- 更新 -->
	   <update id="updateUser" parameterType="com.mybatis.domain.User">
	   UPDATE user SET name= #{name},description= #{description} WHERE id = #{id}
	   </update>
	   <!--查詢全部-->
	   <select id="getAllUsers" resultType="com.mybatis.domain.User">
	   	SELECT * FROM user;
	   </select>
</mapper>

##完成簡單CRUD 建立一個測試類

/**
 * @Author {LearnAndGet}
 * @Time 2018年12月24日
 * @Discription:
 */
package com.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import com.mybatis.domain.User;

public class Test {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		//1.讀取配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		//2.根據配置文件建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//3.SqlSessionFactory建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//4.SqlSession執行statement,並返回映射結果
		

		//查詢測試
		User user = sqlSession.selectOne("com.mybatis.mapping.userMapper.getUser",1);
		System.out.println(user);
		
		//查詢全部
		List users = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users);
		
		//插入測試
		User user2 = new User();
		user2.setName("Knight");
		user2.setDescription("a killer");
		sqlSession.insert("com.mybatis.mapping.userMapper.addUser", user2);
		//再次查詢全部
		List users2 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users2);
		
		//刪除測試
		sqlSession.delete("com.mybatis.mapping.userMapper.deleteUser",1);
		//再次查詢全部
		List users3 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users3);
		
		//更新測試(先查出一個後更新)
		User oldUser = sqlSession.selectOne("com.mybatis.mapping.userMapper.getUser",3);
		oldUser.setName("GodV");
		sqlSession.update("com.mybatis.mapping.userMapper.updateUser", oldUser);
		//再次查詢全部
		List users4 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users4);
				
		sqlSession.close();
	}
}

輸出結果以下

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1988859660.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - ==>  Preparing: SELECT * FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
User [id=1, name=uzi, description=a gun]
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=1, name=uzi, description=a gun], User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man]]
DEBUG [main] - ==>  Preparing: INSERT INTO user(name,description) VALUES(?,?) 
DEBUG [main] - ==> Parameters: Knight(String), a killer(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 5
[User [id=1, name=uzi, description=a gun], User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - ==>  Preparing: DELETE FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - ==>  Preparing: SELECT * FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - ==>  Preparing: UPDATE user SET name= ?,description= ? WHERE id = ? 
DEBUG [main] - ==> Parameters: GodV(String), ChampionMid(String), 3(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=GodV, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - Rolling back JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Returned connection 1988859660 to pool.

#總結 由上述步驟來看,使用Mybatis來完成一個入門的數據庫查詢並不困難,一共有如下幾個步驟:

  1. 建立Mybatis的xml配置文件,該配置文件主要約束了Mybatis的行爲,包括數據庫鏈接以及sql映射文件位置等
  2. 建立sql映射的配置文件,在該文件中,將指定的sql語句綁定到一個關鍵字上
  3. 建立SqlSession對象,使用SelectOne方法,執行"命名空間+關鍵字",並附帶一個查詢參數,便可完成查詢。
相關文章
相關標籤/搜索