天天看點

【Mybatis學習筆記】—— 【三】sql映射檔案一、增删改查 insert、update、delete、select二、insert 擷取自增主鍵的值三、參數處理三、select 元素

需要更好的閱讀的體驗請移步 👉 小牛肉的個人部落格 👈

文章目錄

  • 一、增删改查 insert、update、delete、select
  • 二、insert 擷取自增主鍵的值
  • 三、參數處理
    • 1. 單個參數
    • 2. 多個參數
    • 3. @Param 命名參數
    • 4. POJO
    • 5. Map
    • 6. TO
    • 參數處理綜合示例
    • 參數處理 $ 和 # 的差別
  • 三、select 元素
    • 1. resultType 傳回值類型
      • a. 傳回 List
      • b. 傳回 Map
        • 傳回一條記錄
        • 傳回多條記錄
    • 2. resultMap 自定義結果集映射規則
    • 3. resultMap 聯合查詢:級聯屬性封裝結果集
    • 4. resultMap association:嵌套結果集
    • 5. resultMap association:分步查詢
    • 5. resultMap association:分步查詢 & 延遲加載
    • 6. resultMap collection:嵌套結果集
    • 7. resultMap collection:分步查詢
    • 8. resultMap collection:多列值封裝map & 懶加載
    • 9. resultMap discriminator 鑒别器

映射檔案指導着MyBatis如何進行資料庫增删改查, 有着非常重要的意義;

  • cache –命名空間的二級緩存配置
  • cache-ref – 其他命名空間緩存配置的引用
  • resultMap – 自定義結果集映射
  • parameterMap – 已廢棄!老式風格的參數映射
  • sql –抽取可重用語句塊。
  • insert – 映射插入語句
  • update – 映射更新語句
  • delete – 映射删除語句
  • select – 映射查詢語句

一、增删改查 insert、update、delete、select

select

元素在第一章已經學習過了,接下來看

insert

,

update

,

delete

元素,在第一章代碼的基礎上完成一套完整的 CRUD 流程

sql映射檔案:

<mapper namespace="com.smallbeef.mybatis.dao.EmployeeMapper">
    <!--id:唯一辨別
    resultType: 傳回值類型
    #{id}:從傳遞過來的參數中取出id值-->

    <!--public Employee getEmpById(Integer id)
    将唯一辨別id和接口中的方法進行綁定-->
    <select id="getEmpById" resultType="com.smallbeef.mybatis.bean.Employee">
        select id, last_name lastName, email, gender from tbl_employee where id = #{id}
    </select>

    <!--public Integer addEmp(Employee employee);-->
    <insert id = "addEmp">
        insert into tbl_employee(last_name, email, gender) values(#{lastName}, #{email}, #{gender})
    </insert>

    <!--public boolean updateEmp(Employee employee);-->
    <update id="updateEmp" >
        update tbl_employee
        set last_name = #{lastName}, email = #{email}, gender = #{gender}
        where id = #{id}
    </update>

    <!--public void deleteEmpById(Integer id);-->
    <delete id="deleteEmpById">
        delete from tbl_employee
        where id = #{id}
    </delete>


</mapper>
           

mybatis允許增删改直接定義以下類型傳回值

  • Integer
  • Long
  • Boolean
  • void

Dao層接口類:

public interface EmployeeMapper {

    /**
     * 查找
     * @param id
     * @return
     */
    public Employee getEmpById(Integer id);

    /**
     * 更新
     * @param employee
     * @return
     */
    public boolean updateEmp(Employee employee);

    /**
     * 添加
     * @param employee
     * @return
     */
    public Integer addEmp(Employee employee);

    /**
     * 删除
     * @param id
     */
    public void deleteEmpById(Integer id);
}
           

同時别忘了在JavaBean類中添加無參構造函數和構造函數,以及在全局配置檔案中注冊sql映射檔案

/**
     * 測試增删改
     *   * 1、mybatis允許增删改直接定義以下類型傳回值
     * 	 * 		Integer、Long、Boolean、void
     * 	 * 2、我們需要手動送出資料
     * 	 * 		sqlSessionFactory.openSession();===》手動送出
     * 	 * 		sqlSessionFactory.openSession(true);===》自動送出
     * @throws IOException
     */
    @Test
    public void test02() throws  IOException{
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

            // 測試插入
            Employee jack = new Employee(null, "Jack", "1", "[email protected]");
            mapper.addEmp(jack);

            // 測試修改
            Employee jack123 = new Employee(2, "Jack123", "0", "[email protected]");
            mapper.updateEmp(jack123);

            // 測試删除
            mapper.deleteEmpById(2);

            //必須手動送出資料
            sqlSession.commit();

        }finally {
            sqlSession.close();
        }

    }
           

注意一定要手動送出資料

sqlSession.commit();

因為我們是這樣打開的

sqlSessionFactory.openSession();

可以通過

sqlSessionFactory.openSession(true);

來設定自動送出

二、insert 擷取自增主鍵的值

若資料庫支援自動生成主鍵的字段(比如 MySQL 和 SQL Server),

則可以設定

useGeneratedKeys=”true”

,然後再把

keyProperty

設定到目标屬性上。

<insert id="addEmp" parameterType="com.smallbeef.mybatis.bean.Employee"
		useGeneratedKeys="true" keyProperty="id">
		insert into tbl_employee(last_name,email,gender) 
		values(#{lastName},#{email},#{gender})
</insert>
           

三、參數處理

1. 單個參數

單個參數:mybatis不會做特殊處理,

#{參數名/任意名}:取出參數值。

例如:

不一定非要通過

#{id}

取出參數值,任意參數名都可取出,比如

#{abc}

<select id="getEmpById" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where id = #{abc}
</select>
           

2. 多個參數

多個參數的情況下,按照上面的方法取值會報錯,比如:

public Employee getEmpByIdAndLastName(Integer id,String lastName);

-------------------------------------------------------------------

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 </select>
           

報錯如下:

org.apache.ibatis.binding.BindingException: 
	Parameter 'id' not found. 
	Available parameters are [1, 0, param1, param2]
           

任意多個參數,都會被MyBatis重新包裝成一個Map傳入。

key:param1…paramN, 或者參數的索引也可以

value:傳入的參數值

#{ }就是從map中擷取指定的key的值;

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{param1} and last_name=#{param2}
 </select>
           

3. @Param 命名參數

多個參數用上述這樣的方法看起來不太直覺,于是我們可以使用注解

@Param

為參數起一個名字,MyBatis就會将這些參數封 裝進map中,key就是我們自己指定的名字

舉例如下:

public Employee getEmpByIdAndLastName(@Param("id")Integer id,@Param("lastName")String lastName);

---------------------------------------------------------------------------------------

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 </select>
           

4. POJO

如果多個參數正好是我們業務邏輯的資料模型,我們就可以直接傳入pojo;

#{屬性名}:取出傳入的pojo的屬性值

舉例如下:

public boolean updateEmp(Employee employee);

-------------------------------------------------------------

<update id="updateEmp">
		update tbl_employee 
		set last_name=#{lastName},email=#{email},gender=#{gender}
		where id=#{id}
</update>
           

5. Map

如果多個參數不是業務模型中的資料,沒有對應的pojo,不經常使用,為了友善,我們也可以封裝多個參數為map,直接傳遞

#{key}:取出map中對應的值

舉例如下:

public Employee getEmpByMap(Map<String, Object> map);

---------------------------------------------------------------------

<select id="getEmpByMap" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id=${id} and last_name=#{lastName}
</select>
           
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("lastName", "Tom");
Employee employee = mapper.getEmpByMap(map);
           

6. TO

如果多個參數不是業務模型中的資料,但是經常要使用,推薦來編寫一個

TO(Transfer Object)

資料傳輸對象

比如分頁模型

Page{
	int index;
	int size;
	......
}
           

參數處理綜合示例

取值:

  • id —> #{id / param1}
  • lastName —> #{param2}

取值:

  • id —> #{param1}
  • lastName —> #{param2.lastName / e.lastName}

特别注意:

如果是Collection(List、Set)類型或者是數組,也會特殊處理。也是把傳入的list或者數組封裝在map中。

  • Collection:則對應 key 為 collection
  • List:則對應 key 為 collection 或者 list

舉例如下:

取值:

取出第一個id的值: # {list[0]}

參數處理 $ 和 # 的差別

  • #{}

    :可以擷取map中的值或者pojo對象屬性的值;
  • ${}

    :可以擷取map中的值或者pojo對象屬性的值;

輸出如下:

Preparing: select * from tbl_employee where id=2 and last_name=?

差別:

  • #{}: 是以預編譯的形式,将參數設定到sql語句中,防止sql注入
  • ${}: 取出的值直接拼裝在sql語句中;會有安全問題;

大多情況下,我們去參數的值都應該去使用#{};

原生jdbc不支援占位符的地方我們就可以使用${}進行取值

比如分表、排序。。。;

舉例如下:

按照年份分表拆分

select * from ${year}_salary where xxx;
select * from tbl_employee order by ${f_name} ${order}
           

三、select 元素

Select元素來定義查詢操作。

  • Id:唯一辨別符。 – 用來引用這條語句,需要和接口的方法名一緻
  • parameterType:參數類型。 – 可以不傳,MyBatis會根據TypeHandler自動推斷
  • resultType:傳回值類型。 – 别名或者全類名,如果傳回的是集合,定義集合中元 素的類型。不能和 resultMap 同時使用

1. resultType 傳回值類型

傳回類型是對象的情況我們之前已經反複使用過了,下面來講解以下其他傳回類型

a. 傳回 List

如果傳回的是集合,resultType 中定義集合中元素的類型,比如下面代碼中的 Employee

public List<Employee> getEmpsByLastNameLike(String lastName);
	
--------------------------------------------------------------

	<!--resultType:如果傳回的是一個集合,要寫集合中元素的類型  -->
	<select id="getEmpsByLastNameLike" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where last_name like #{lastName}
	</select>
           

測試:

List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
			for (Employee employee : like) {
				System.out.println(employee);
}
           

b. 傳回 Map

resultmap = "map"

傳回一條記錄

傳回一條記錄的map;key就是列名,值就是對應的值

public Map<String, Object> getEmpByIdReturnMap(Integer id);

-------------------------------------------------------

<select id="getEmpByIdReturnMap" resultType="map">
 		select * from tbl_employee where id=#{id}
</select>
           

測試:

Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
			System.out.println(map);
           

結果:

{id = 1, [email protected], last_name = Jack, gender = 0}

傳回多條記錄

  • 多條記錄封裝一個map:

    Map<Integer,Employee>

    : 鍵是這條記錄的主鍵,值是記錄封裝後的javaBean
  • @MapKey

    : 告訴mybatis封裝這個map的時候使用哪個屬性作為map的key
@MapKey("lastName")
	public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);

-----------------------------------------------------------------------

<select id="getEmpByLastNameLikeReturnMap" 	
	resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where last_name like #{lastName}
</select>
           

測試:

Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
			System.out.println(map);
           

結果:

{Jack = Employee[id = 1, lastName = Jack, email = [email protected], gender = 0],Tom = Employee[id = 2, lastName = Tom, email = [email protected], gender = 1]}

2. resultMap 自定義結果集映射規則

resultType

自定義某個javaBean的封裝規則

參數:

  • type:自定義規則的 JavaBean 類型
  • id:唯一id友善引用

标簽:

  • id : 定義主鍵
  • result:定義其他普通鍵

标簽屬性:

  • column : 資料庫表的列名
  • property : 對應的JavaBean屬性
<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MySimpleEmp">
	<!--指定主鍵列的封裝規則
	id 定義主鍵會底層有優化;
		column:指定哪一列
		property:指定對應的javaBean屬性
	result 定義普通列封裝規則 
	 -->
	<id column="id" property="id"/>
	
	
	<result column="last_name" property="lastName"/>
	<!-- 其他不指定的列會自動封裝:但是 推薦 我們隻要寫resultMap就把全部的映射規則都寫上-->
	<result column="email" property="email"/>
	<result column="gender" property="gender"/>
</resultMap>

<!-- resultMap:自定義結果集映射規則;  -->
<!-- public Employee getEmpById(Integer id); -->
<select id="getEmpById"  resultMap="MySimpleEmp">
	select * from tbl_employee where id=#{id}
</select>
           

3. resultMap 聯合查詢:級聯屬性封裝結果集

  • POJO中的屬性可能會是一個對象
  • 我們可以使用聯合查詢,并以級聯屬性的方式封裝對象。

例如:

員工表中含有部門對象

實體類:

public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	private Department dept;


--------------------------------------------------

public class Department {
	private Integer id; //資料庫表字段id
	private String departmentName; //資料庫表字段dept_name
           

接口:

映射檔案:

employee中内嵌對象dept的屬性通過dept.id、dept.departmentName等來擷取

<!--
		聯合查詢:級聯屬性封裝結果集
	  -->
	<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyDifEmp">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		<result column="did" property="dept.id"/>
		<result column="dept_name" property="dept.departmentName"/>
	</resultMap>

<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>
           

4. resultMap association:嵌套結果集

使用association定義關聯的單個對象的封裝規則

association

标簽可以指定聯合的 javaBean 對象

  • property

    = “dept” :指定哪個屬性是聯合的對象
  • javaType

    : 指定這個屬性對象的類型[不能省略]
<!-- 
		使用association定義關聯的單個對象的封裝規則;
	 -->
	<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyDifEmp2">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--  association可以指定聯合的javaBean對象
		property="dept":指定哪個屬性是聯合的對象
		javaType:指定這個屬性對象的類型[不能省略]
		-->
		<association property="dept" javaType="com.smallbeef.mybatis.bean.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
	</resultMap>

<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp2">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>
           

5. resultMap association:分步查詢

使用

association

進行分步查詢:

  • 先按照員工 id 查詢員工資訊
  • 根據查詢到的員工資訊中的 d_id 值去部門表查出部門資訊
  • 将部門資訊設定到員工中;

association 标簽的相關屬性

  • select

    : 表明目前屬性是調用select指定的方法查出的結果
  • column

    : 指定将哪一列的值傳給這個方法

流程 :使用 select 指定的方法(傳入column 指定的這列參數的值)查出對象,并封裝給 property 指定的屬性

<!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- association定義關聯對象的封裝規則
	 		select:表明目前屬性是調用select指定的方法查出的結果
	 		column:指定将哪一列的值傳給這個方法
	 		
	 		流程:使用select指定的方法(傳入column指定的這列參數的值)查出對象,并封裝給property指定的屬性
	 	 -->
 		<association property="dept" 
	 		select="com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>
           

其中,根據部門id查詢部門資訊 getDeptById 如下:

public Department getDeptByIdStep(Integer id);

-------------------------------------------

<select id="getDeptById" resultType="com.smallbeef.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>
           

5. resultMap association:分步查詢 & 延遲加載

在分步查詢基礎上實作延遲加載(懶加載)

在全局配置檔案中開啟延遲加載和屬性按需加載

<settings>	
		<!--顯示的指定每個我們需要更改的配置的值,即使他是預設的。防止版本更新帶來的問題  -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
           

6. resultMap collection:嵌套結果集

場景:查詢部門的時候将部門對應的所有員工資訊也查詢出來

部門表對應的JavaBean,内嵌員工資訊的集合屬性

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
           
public List<Employee> getEmpsByDeptId(Integer deptId);

--------------------------------------------

	<select id="getEmpsByDeptId" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>
           

collection

标簽定義關聯集合類型的屬性的封裝規則

參數:

  • property

    :指定要封裝到哪個集合屬性(本例中封裝到部門對象中的 emps 屬性)
  • ofType

    : 指定集合裡面元素的類型
<!--嵌套結果集的方式,使用collection标簽定義關聯的集合類型的屬性封裝規則  -->
	<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定義關聯集合類型的屬性的封裝規則 
			ofType:指定集合裡面元素的類型
		-->
		<collection property="emps" ofType="com.smallbeef.mybatis.bean.Employee">
			<!-- 定義這個集合中元素的封裝規則 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>


	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>
	
           

7. resultMap collection:分步查詢

需求:根據部門id查詢該部門下所有的員工資訊

  • 根據部門id查詢部門資訊
  • 根據部門id查詢員工資訊
<!-- collection:分段查詢 -->
<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDeptStep">
	<id column="id" property="id"/>
	<id column="dept_name" property="departmentName"/>
	<collection property="emps" 
		select="com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
		column="id">
	</collection>
</resultMap>


<!-- public Department getDeptByIdStep(Integer id); -->
<select id="getDeptByIdStep" resultMap="MyDeptStep">
	select id,dept_name from tbl_dept where id=#{id}
</select>
           

其中根據部門id查詢員工資訊 getEmpsByDeptId

public List<Employee> getEmpsByDeptId(Integer deptId);

-------------------------------------------

	<select id="getEmpsByDeptId" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>
           

8. resultMap collection:多列值封裝map & 懶加載

分步查詢的時候通過column指定,将對應的列的資料 傳遞過去,我們有時需要傳遞多列資料 :将多列的值封裝map傳遞;

column="{key1=column1,key2=column2}"

key是方法中的形參,column是資料庫表列名

fetchType="lazy"

:表示使用延遲加載,該标簽可以覆寫全局的延遲加載政策

  • lazy:延遲
  • eager:立即
<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>
           

9. resultMap discriminator 鑒别器

鑒别器:mybatis可以使用

discriminator

判斷某列的值,然後根據某列的值改變封裝行為

<discriminator javaType=" " column = " "></discriminator>

屬性:

  • column:指定判定的列名
  • javaType:列值對應的java類型

場景:

  • 如果查出的是女生:就把部門資訊查詢出來,否則不查詢;
  • 如果是男生,把last_name這一列的值指派給email;
<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyEmpDis">
 	<id column="id" property="id"/>
 	<result column="last_name" property="lastName"/>
 	<result column="email" property="email"/>
 	<result column="gender" property="gender"/>
 	<!--
 		column:指定判定的列名
 		javaType:列值對應的java類型  -->
 	<discriminator javaType="String" column="gender">
 		<!--女生  resultType:指定封裝的結果類型;不能缺少-->
 		<case value="0" resultType="com.smallbeef.mybatis.bean.Employee">
 			<association property="dept" 
		 		select="com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById"
		 		column="d_id">
	 		</association>
 		</case>
 		<!--男生 ;如果是男生,把last_name這一列的值指派給email; -->
 		<case value="1" resultType="com.smallbeef.mybatis.bean.Employee">
	 		<id column="id" property="id"/>
		 	<result column="last_name" property="lastName"/>
		 	<result column="last_name" property="email"/>
		 	<result column="gender" property="gender"/>
 		</case>
 	</discriminator>
 </resultMap>
           

繼續閱讀