1. 程式人生 > >Java框架(七)之Mybatis(簡介、mybatis開發dao的方式)

Java框架(七)之Mybatis(簡介、mybatis開發dao的方式)

一、Mybatis簡介

1.定義

MyBatis 是支援普通 SQL 查詢,儲存過程和高階對映的優秀持久層(dao)框架。MyBatis 消除 了幾乎所有的 JDBC程式碼和 引數的手工設定 以及對 結果集的檢索。MyBatis 可以使用簡單的 XML 或註解用於配置和原始對映,將介面和 Java 的POJO(Plain Old Java Objects,普通的 Java 物件)對映成資料庫中的記錄。

2.環境搭建

(1)Mybatis配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration>
	<environments default="development"> 
		<environment id="development">
			<!-- 使用jdbc方式控制事務 -->
			<transactionManager type="JDBC"/> 
			<!-- mybatis提供的連線池連結資料
			  未來:mybatis+spring+sprignmvc  這一步交給spring
			 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/> 
				<property name="url" value="jdbc:mysql:///mystu?unicode=true&amp;characterEncoding=utf-8"/>
				<property name="username" value="root"/> 
				<property name="password" value="111"/>
			</dataSource> 
		</environment>
	</environments>
	<!-- mapper配置 -->
	<mappers>
		<mapper resource="com/qf/bean/UserMapper.xml"></mapper>
	
	</mappers>
</configuration>

(2)對映檔案

<!-- namespace指定的實體類的全路徑 -->
<mapper namespace="com.qf.bean.User">
       <!--根據id查詢使用者的方法 
       id="selectById"  在同一個檔案中唯一
       parameterType="int"  引數型別
       resultType="com.qf.bean.User" 返回值型別
        --> 
	<select id="selectById" parameterType="int" resultType="com.qf.bean.User">
		select * from user where id=#{id}
	</select>
	<!-- 全查 
		resultType:指定該 sql語句的結果集(每一行對應的)
	-->
	<select id="findAll" resultType="com.qf.bean.User" >
		select * from User
	</select>
	<!-- 新增 
		如果引數為物件的話,sql語句中的佔位變數應該與資料庫中的保持一致
	-->
	<insert id="saveUser" parameterType="com.qf.bean.User">
		insert into User(username,password) values(#{username},#{password})
	</insert>
	<!-- 修改 -->
	<update id="updateUser" parameterType="com.qf.bean.User">
		update User set password=#{password} where id=#{id}
	</update>
	<!-- 刪除 -->
	<delete id="deleteById">
		delete from User where id=#{id}
	</delete>
	<!-- 新增+返回自增主鍵 -->
	<!-- <insert id="saveUserAndRuturnId" parameterType="com.qf.bean.User">
		配置返回自增主鍵 
		方法一:使用selectKey節點配置
			keyProperty="id":實體類中主鍵的屬性名
			keyColumn="id" :資料庫中為主鍵的列名
			order="AFTER" :執行該sql語句的時機
			resultType="int":該sql語句的返回值型別
		
		<selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
			select last_insert_id()
		</selectKey>
		insert into User(username,password) values(#{username},#{password})
	</insert> -->
	<insert id="saveUserAndRuturnId" parameterType="com.qf.bean.User" useGeneratedKeys="true"
	keyProperty="id" keyColumn="id">
		insert into user(username,password) 
		values(#{username},#{password})
	</insert>
</mapper>

(3)測試類

public class TestMybatis {
	public static void main(String[] args) {
		//1.指定配置檔案
		String Config="MybatisConfig.xml";
		
		try {
			//2.讀取配置檔案
			Reader reader=Resources.getResourceAsReader(Config);
			//3.構建SqlSessionFactory物件
			SqlSessionFactory  sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
			//4.通過SqlSessionFactory獲得SqlSession
			SqlSession sqlSession=sqlSessionFactory.openSession();
			//5.通過SqlSession呼叫對映檔案中的sql檔案
			User user=sqlSession.selectOne("selectById", 2);
			System.out.println(user);
			sqlSession.commit();
			sqlSession.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3.插入資料

  • 主鍵返回之自增主鍵

第一種:

<insert id="saveUserAndRuturnId" parameterType="com.qf.bean.User">
		<!--使用selectKey節點配置
			keyProperty="id":實體類中主鍵的屬性名
			keyColumn="id" :資料庫中為主鍵的列名
			order="AFTER" :執行該sql語句的時機
			resultType="int":該sql語句的返回值型別-->
		
		<selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
			select last_insert_id()
		</selectKey>
		insert into User(username,password) values(#{username},#{password})
	</insert>

第二種:

<insert id="saveUserAndRuturnId" parameterType="com.qf.bean.User" useGeneratedKeys="true"
	keyProperty="id" keyColumn="id">
		insert into user(username,password) 
		values(#{username},#{password})
	</insert>
  • 主鍵返回值UUID UUID函式是mysql的函式

      <insert id="saveUsersReturnId" parameterType="cm.itqf.pojo.Users">
         		<!-- 
         		select uuid():mysql的函式  能夠生成一個隨機字串
         		keyColumn="id"   表中為主鍵的列名
         		keyProperty="id"  表中為主鍵的屬性名
         		resultType="String"  主鍵的型別
         		order="BEFORE" 執行時機  在新增語句的前執行
         		 -->
         		<selectKey keyColumn="id" keyProperty="id" resultType="String" order="BEFORE">
         			select UUID()
         		</selectKey>
         		insert into users(id,username,password) values(#{id},#{username},#{password})
          </insert>
    

二、mybatis開發dao的方式

  • 原始dao層開發方式(例)

MybatisUtils工具類

public class MybatisUtils {
	static SqlSession sqlSession;
	static SqlSessionFactory sqlSessionFactory;
	static{
	try {
		sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("MybatisConfig.xml"));
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	}
	public static SqlSession getSqlSession(){
		return sqlSessionFactory.openSession();
		
	}
}

UserDaoimpl實現類

public class UserDaoImpl implements UserDao{
	public void saveUser(User u) {
		// TODO Auto-generated method stub
		SqlSession sqlSession=MybatisUtils.getSqlSession();
		sqlSession.insert("saveUser",u);
		sqlSession.commit();
		sqlSession.close();
	}
	public User selectById(int id) {
		SqlSession sqlSession=MybatisUtils.getSqlSession();
		User user=sqlSession.selectOne("selectById",id);
		sqlSession.commit();
		sqlSession.close();
		return user;
	}
}

UserMapper 對映檔案

 <!-- namespace指定的實體類的全路徑 -->
<mapper namespace="com.qf.bean.User">
       <!--根據id查詢使用者的方法 
       id="selectById"  在同一個檔案中唯一
       parameterType="int"  引數型別
       resultType="com.qf.bean.User" 返回值型別
        --> 
	<select id="selectById" parameterType="int" resultType="com.qf.bean.User">
		select * from user where id=#{id}
	</select>
	<!-- 全查 
		resultType:指定該 sql語句的結果集(每一行對應的)
	-->
	<select id="findAll" resultType="com.qf.bean.User" >
		select * from User
	</select>
	<!-- 新增 
		如果引數為物件的話,sql語句中的佔位變數應該與資料庫中的保持一致
	-->
	<insert id="saveUser" parameterType="com.qf.bean.User">
		insert into User(username,password) values(#{username},#{password})
	</insert>
</mapper>

注意:

SqlSessionFactory,它的生命週期,應該是應用範圍,全域性範圍只有一個工廠,使用單例模式來實現這個功 能。與spring整合之後,由spring來對其進行單例管理。 SqlSession,它內部含有一塊資料區域,存線上程不安全的問題,所以應該將sqlsession宣告到方法內部。