Mybatis動態sql及性能優化-3


內容簡介

1.回顧
2.動態sql
3.性能優化
  懶加載機制
  一級緩存
  二級緩存

一.回顧

1.config文件常用標簽
   properties標簽:引入外部properties文件資源。
   settings標簽:設置mybatis全局行為。
   typeAlias標簽:減少mapper文件配置,給模型類起別名。
   transactionManager標簽:配置mybatis的事務行為(JDBC|MANAGED)
   dataSource標簽:配置mybatis數據源(POOLED|UNPOOLED|JNDI)
   mappers標簽:引入Mapper文件或接口(url|resources|class|package)
2.Mapper文件常用標簽
  a. resultMap標簽:對查詢的結果進行封裝處理
  				簡單pojo類型處理,只需處理表中字段和對像中屬性映射處理。
  				包裝pojo類型處理,使用Collection處理包裝集合類型的對像,association處理包含單個pojo對像。
  		Collection處理的兩種方式:
        			1.連接查詢join
        			2.通過多條select查詢的方式。
        association處理兩種方式:
        			1.連接查詢join
        			2.通過多條select查詢的方式。
   
   		discriminor鑒別器:根據查詢結果中某個字段作為標識符,根據其查詢的值,進行分類封裝處理。
   	
   b.主鍵映射策略:如果主鍵由數據庫生成,而不是手動指定,怎么獲取該主鍵的問題。
   				一般使用selectKey標簽處理。
  3.自定義封裝結果集(了解):
  	按照自已定義方式把數據庫返回結果封裝成自己想要的類型。
  	一般自己建立結果的處理類,實現ResultHandler接口,重寫里面的方法。
  	一般在select("statementId",params,ResultHandler實現類對像)

二.動態Sql

1.解決什么樣問題

用來解決sql語句where后條件的拼接問題,
使用流程控制標簽來完成條件的拼接:if標簽,where標簽,foreach標簽。。。。

2.常用動態sql標簽

1.if標簽
2.choose when otherwise標簽
3.trim標簽
4.foreache標簽
5.where標簽
6.set標簽
2.1 if標簽
和java中的if語句類似。
	<select id="selectByItem" parameterType="User" resultType="User">
		select * from USER 
		where 1=1
        <!--mybatis如果是低版本時,如果是整形值,不要用‘’來判斷;3.4.6版本沒有問題-->
		<if test="id != null and id !=''">
			and id = #{id}
		</if>
		<if test="username !=null and username !=''">
			and username=#{username}
		</if>
		<if test="password !=null and password !=''">
			and password=#{password}
		</if>
		<if test="address !=null and address !=''">
			and address=#{address}
		</if>	 
	</select>
2.2 where標簽
根據查詢條件是否存在,來決定是否生成where字符串。
可以去除where后面緊跟的sql關鍵字, 如or或and
<!-- where標簽 -->
	<select id="selectByItem2" parameterType="User" resultType="User">
		select * from USER
		<where>
			<if test="id !='' and id != null">
				and id = #{id}
			</if>
			<if test="username !=null and username !=''">
				and username=#{username}
			</if>
			<if test="password !=null and password !=''">
				and password=#{password}
			</if>
			<if test="address !=null and address !=''">
				and address=#{address}
			</if>
		</where>	 
	</select>
2.3 choose when otherwise
和java中switch case作用類似。
不管有多少條件滿足,只拼接其中一個條件。
<!-- choose when otherwise -->
	
	<select id="selectByItem3" parameterType="User" resultType="User">
		select * from USER
		<where>
			<choose>
				<when test="id !='' and id != null">
					and id = #{id}
				</when>
				<when test="username !=null and username !=''">
					and username=#{username}
				</when>
				<when test="password !=null and password !=''">
					and password=#{password}
				</when>
				<when test="address !=null and address !=''">
					and address=#{address}
				</when>
				<otherwise>
					and 1=1
				</otherwise>
			</choose>
		</where>	 
	</select>
2.4 Set標簽
set用法和上面where用法一致。
可以生成update語句中的set關鍵字,也可去除sql關鍵字,如逗號(set標簽中sql字符串最后的逗號)
<update id="update" parameterType="User">
		update USER
		<set>
			<if test="username !=null and username !=''">
				username = #{username},
			</if>
			<if test="password !=null and password !=''">
				password=#{password},
			</if>
			<if test="address !=null and address !=''">
				address=#{address},
			</if>
		</set>
		where id = #{id}
	</update>
2.5 foreach標簽
類似於java中的foreach迭代。把傳入sql語句中的數組類型或集合類型數據進行遍歷操作。
	<!-- 接口中參數為數組時,collection值必須為array -->
	<select id="selectByIds" resultType="User">
		select * from USER 
		<foreach collection="array" item="id" open="where id in(" separator="," close=")">
			#{id}
		</foreach>
	</select>

	<!-- 接口中參數為pojo,collection值必須為該數組類型屬性名 -->
	<select id="selectByIds2" resultType="User" parameterType="User">
		select * from USER 
		<foreach collection="ids" item="id" open="where id in(" separator="," close=")">
			#{id}
		</foreach>
	</select>
2.6 trim標簽
可以刪除sql語句指定的字符串。
<!--
	prefix="前綴":在后面sql字符串前面拼接指定的前綴。
	prefixOverrides="要去除的字符":把緊跟着前綴后面的字符去掉。
	suffix="后綴":在后面sql字符串后面拼接指定的后綴。
	suffixOverrides="要去除的字符":把緊跟着后綴前面的字符去掉。
-->

<update id="update2" parameterType="User">
		update USER
			<trim prefix="set" prefixOverrides=",">
				<if test="username !=null and username !=''">
				,username = #{username}
				</if>
				<if test="password !=null and password !=''">
				,password=#{password}
				</if>
				<if test="address !=null and address !=''">
				,address=#{address}
				</if>
			</trim>
		where id = #{id}
	</update>
	
	<update id="update3" parameterType="User">
		update USER
			<trim prefix="set" suffixOverrides=",">
				<if test="username !=null and username !=''">
				username = #{username},
				</if>
				<if test="password !=null and password !=''">
				password=#{password},
				</if>
				<if test="address !=null and address !=''">
				address=#{address},
				</if>
			</trim>
		where id = #{id}
	</update>

三.性能優化

1.懶加載機制(lazy)

當進行多表關聯查詢時,如果關聯中數據暫時用不到,可以不去查詢,當用到的時候,再發送sql語句去數據庫關聯出來。
目的是:減少與數據庫的交互行為,即減少數據庫的開消。
注意:
join查詢不支持lazy,多條select查詢才支持lazy!

2.步驟

1.在setting標簽中設置lazy開關
	<settings>
		<!-- 開啟lazy加載 -->
		<setting name="lazyLoadingEnabled" value="true"/>
	</settings>
2.使用select方式進行關聯查詢

Model類

//User類
public class User {

	private Integer id;
	private String username;
	private String password;
	private String address;
	
	private List<Orders> list;
}
    
//Orders類
public class Orders {
	
	private int id;
	private String oname;
	private int oprice;
    
}

UserMapper接口

public interface UserMapper {	
	public User selectById(User user);
}

UserMapper.xml

<mapper namespace="lazy.mapper.UserMapper">

	<resultMap type="Users" id="baseResultMap">
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="password" property="password"/>
		<!-- 關聯集合數據,其中ofType用來說明集合中的數據類型 -->
		<collection property="list" ofType="Orders" select="lazy.mapper.OrdersMapper.selectByUid" column="id"></collection>
	</resultMap>
	
	<select id="selectById"  resultMap="baseResultMap">
		select * from USER where id = #{id}
	</select>
	
</mapper>

OrdersMapper接口

public interface OrdersMapper {
	public List<Orders> selectByUid(int uid);
}

OrdersMapper.xml

<mapper namespace="lazy.mapper.OrdersMapper">

	<select id="selectByUid" resultType="Orders">
			select * from orders where uid = #{uid}
	</select>

</mapper>

UserService類

public class UserService {

	public User findById(User user) {

		SqlSession session = MybatisUtil.findSqlSession();

		UserMapper mapper = session.getMapper(UserMapper.class);

		User findUser = mapper.selectById(user);

		session.close();

		return findUser;

	}

}

Test類

public class TestLazy {

	UserService ser = new UserService();
	
	@Test
	public void testLazy(){
		
		User user = new User();
		user.setId(1);
		User findUser = ser.findById(user);
		//當只使用User表中數據時,只發送一條查詢User表的sql語句。
		System.out.println(findUser.getUsername());
		//當主動使用關聯表中數據時,mybaits才再次發送查詢語句去查詢關聯表。如果不使用,則該條sql將不會發送給數據庫。
		//System.out.println(findUser.getList());
	}
}

3.一級緩存

3.1緩存概念
目的,減少與數據庫的交互行為,當讀取同一條數據時,優先從內存中的緩存中讀取,如果能讀到數據(命中數據),則就不需要交互數據庫,如果讀不到,則會交互數據庫,查尋內容,放在緩存中,以備下一次查詢時,在緩存中能命中數據,提高程序響應速度。
3.2 mybatis的一級緩存
1.一級緩存是默認使用的。
2.一級緩存指的就是sqlsession范圍內緩存,在sqlsession中有一個數據區域,是map結構,這個區域就是一級緩存區
域。一級緩存中的key是由sql語句、條件、statement等信息組成一個唯一值。一級緩存中的value,就是查詢出的結果
對象。
3.當數據庫對應表發生增刪改時,並執行commit操作時,默認會刷新一級緩存。
如下圖所示:

第一次發起查詢用戶id為1的用戶信息,先去找緩存中是否有id為1的用戶信息,如果沒有,從數據庫查詢用戶信
息。得到用戶信息,將用戶信息存儲到一級緩存中。
如果sqlSession去執行commit操作(執行插入、更新、刪除),清空SqlSession中的一級緩存,這樣做的目的為
了讓緩存中存儲的是最新的信息,避免臟讀。
第二次發起查詢用戶id為1的用戶信息,先去找緩存中是否有id為1的用戶信息,緩存中有,直接從緩存中獲取用戶
信息
3.3緩存測試

UserMapper.xml

<mapper namespace="cache1.mapper.UserMapper">
	<select id="selectById"  resultType="cache1.model.User">
		select * from USER where id = #{id}
	</select>
</mapper>

UserMapper接口

public interface UserMapper {
	public User selectById(User user);
}

UserService類

public class UserService {

	public User findById(User user) {

		SqlSession session = MybatisUtil.findSqlSession();

		UserMapper mapper = session.getMapper(UserMapper.class);

		//查詢兩次
		User findUser = mapper.selectById(user);
		System.out.println(findUser.getUsername());
		
        //如果不執行commit(),則發現執行兩次查詢時,只發送一條sql到數據庫,則驗證一級緩存存在。
		//當執行commit()操作時,mybatis上下文會默認你進行增刪改數據了,則會清空一級緩存;
		session.commit(true);
		
		User findUser2 = mapper.selectById(user);
		
		System.out.println(findUser+"===="+findUser2.getUsername());

		session.close();

		return null;

	}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM