1. 程式人生 > >Mybatis-Dao層開發之Mapper介面

Mybatis-Dao層開發之Mapper介面

相關連結:

Mapper介面開發方法只需要程式設計師編寫Mapper介面(相當於Dao介面),由Mybatis框架根據介面定義建立介面的動態代理物件,代理物件的方法體同上邊Dao介面實現類方法。

Mapper介面開發需要遵循以下規範:

1、  Mapper.xml檔案中的namespace與mapper介面的類路徑相同。

2、  Mapper介面方法名和Mapper.xml中定義的每個statement的id相同

3、  Mapper介面方法的輸入引數型別和mapper.xml中定義的每個sql 的parameterType的型別相同

4、  Mapper介面方法的輸出引數型別和mapper.xml中定義的每個sql的resultType的型別相同

1、Mapper對映檔案

定義mapper對映檔案UserMapper.xml(內容同Users.xml),需要修改namespace的值為UserMapper介面路徑。將UserMapper.xml放在classpath 下mapper目錄下。

<?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">

<!-- 名稱空間,對sql進行分類化管理(sql隔離) -->
<mapper namespace="com.sw.mapper.UserMapper">
	<!-- 在對映檔案中配置sql語句 -->
	<!-- 通過select執行查詢,id用於標識對映檔案中的sql(Statement-id)
	將sql語句封裝到mappedstatement中
	#{}表示佔位符
	parameterType-指定輸入引數的型別
	#{id}-id表示輸入的引數,引數名稱就是id,如如果輸入引數是簡單型別,#{}中的引數可以任意
	resultType-指定sql輸出結果所對映的java物件型別
	-->
	<!-- 通過id查詢使用者表的記錄 -->
	<select id="findUserById" parameterType="int" resultType="com.sw.po.User">
		select *from user where id=#{id}
	</select>
	
	<!-- 根據使用者名稱稱模糊查詢使用者資訊 -->
	<!-- resultType-指定單條記錄所對映的物件型別 
	${}拼接sql串,接收引數的內容,不加任何修飾,拼接在sql中(存在sql漏洞)
	${}接收輸入引數的內容,如果傳入的型別是簡單型別,${}中只能使用value
	-->
	<select id="findUserByName" parameterType="java.lang.String" resultType="com.sw.po.User">
	    SELECT *FROM USER WHERE username LIKE '%${value}%'
	</select>
	
	<!-- 新增使用者 -->
	<!-- 指定輸入引數型別是pojo(包括使用者資訊)
		#{}中指定pojo(User)屬性名,接收到pojo的屬性值
		Mybatis通過OGNL獲取物件的屬性值
	 -->
	<insert id="insertUser" parameterType="com.sw.po.User">
	    <!-- 獲取剛增加的記錄主鍵 
	    	返回id到poio物件(User)
	    	SELECT LAST_INSERT_ID():得到剛插入金進去記錄的主鍵值,只適用於自增逐主鍵
	    	keyProperty:將查詢到的主鍵值設定到parameterType指定的物件的id屬性
	    	order:指SELECT LAST_INSERT_ID()的執行順序,相對於insert來說(before/after)
	    	resultType:指定SELECT LAST_INSERT_ID()的結果型別
	    -->
	    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
	        SELECT LAST_INSERT_ID()
	    </selectKey>
	    INSERT INTO USER (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
	   
	    <!-- 使用mysql的uuid生成主鍵返回
	    	執行過程:
	    		首先通過uuid得到主鍵,然後將主鍵設定到id屬性中
	    		其次在Inster執行的時候從User物件中取出id的屬性值
	     -->
	   <!--   <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
	         SELECT UUID()
	     </selectKey>
	   INSERT INTO USER (id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})  -->
	</insert>
	
	<!-- 根據id刪除使用者 -->
	<delete id="deleteUser" parameterType="java.lang.Integer">
	    DELETE FROM USER WHERE id=#{id}
	</delete>
	
	<!-- 根據id更新使用者 
		傳入使用者id以及相關更新資訊
		#{id}:從輸入的user物件中獲取user的屬性值
	-->
	<update id="updateUser" parameterType="com.sw.po.User">
	    UPDATE USER SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} WHERE id=#{id}
	</update>
</mapper>
2、Mapper.java-介面檔案

Mapper介面定義有如下特點:

1、Mapper介面方法名與Mapper.xml(UserMapper.xml)中定義的statement的id相同

2、Mapper介面方法的輸入引數型別和mapper.xml(User.xml)中定義的statement的parameterType的型別相同

3、 Mapper介面方法的輸出引數型別和mapper.xml中定義的statement的resultType的型別相同

程式碼如下;

package com.sw.mapper;

import java.util.List;

import com.sw.po.User;

/*
 *@Author swxctx
 *@time 2016年12月1日
 *@Explain:使用mapper介面(使用者管理),相當於dao介面
 */
public interface UserMapper {
	//根據id查詢使用者的資訊
	public  User findUserById(int id)throws Exception;
	//根據使用者名稱檢視使用者列表
	public List<User> findUserByName(String username)throws Exception;
	//新增使用者
	public void insertUser(User user)throws Exception;
	//刪除使用者
	public void deleteUser(int id)throws Exception;
}
3、測試類
package com.sw.mapper.test;

import java.io.InputStream;
import java.util.Date;
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.junit.Before;
import org.junit.Test;

import com.sw.mapper.UserMapper;
import com.sw.po.User;

/*
 *@Author swxctx
 *@time 2016年12月1日
 *@Explain:
 */
public class UserMapperTest {

	 private SqlSessionFactory sqlSessionFactory;
		@Before
		public void setUpBefore() throws Exception {
			//執行其他方法前需要建立SqlSessionFactory
			// mybatis配置檔案
			String resource = "SqlMapConfig.xml";
			// 得到配置檔案流
			InputStream inputStream = Resources.getResourceAsStream(resource);

			// 建立會話工廠,傳入mybatis的配置檔案資訊
			sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
		}
	
	@Test
	public void testFindUserById() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//建立UserMapper物件,mybatis自動生成mapper代理物件
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//呼叫UserMapper方法
		User user = userMapper.findUserById(27);
		sqlSession.close();
		
		System.out.println(user);
	}
	
	@Test
	public void testFindUserByName() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//建立UserMapper物件,mybatis自動生成mapper代理物件
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//呼叫UserMapper方法
		List<User> user = userMapper.findUserByName("王");
		
		sqlSession.close();
		
		System.out.println(user);
	}

	@Test
	public void testInsertUser()throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//建立UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setUsername("李小二");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("廣州");
		
		//呼叫方法
		userMapper.insertUser(user);
		//提交事務
		sqlSession.commit();
		//釋放資源
		sqlSession.close();
	}
	
	@Test
	public void testDeleteUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//建立UserMapper物件,mybatis自動生成mapper代理物件
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//呼叫UserMapper方法
		userMapper.deleteUser(44);
		sqlSession.commit();
		sqlSession.close();
	}
}
注:

selectOne和selectList

動態代理物件呼叫sqlSession.selectOne()和sqlSession.selectList()是根據mapper介面方法的返回值決定,如果返回list則呼叫selectList方法,如果返回單個物件則呼叫selectOne方法。

namespace

mybatis官方推薦使用mapper代理方法開發mapper介面,程式設計師不用編寫mapper介面實現類,使用mapper代理方法時,輸入引數可以使用pojo包裝物件或map物件,保證dao的通用性。