MyBatis学习三

SqlMapConfig.xml

1、properties属性

将数据库连接参数单独配置在db.properties中,只需在SqlMapConfig.xml中加载db.properties的属性值。在SqlMapConfig.xml中就不需要对数据库连接参数硬编码。

将数据库连接参数只配置在db.properties中,原因:方便对参数进行统一管理,其他xml可以引用该db. properties。

注意:MyBatis将按照下面的顺序来加载属性:

在properties元素内定义的属性首先被读取;

然后会读取properties元素中resource或url加载的属性,它会覆盖已读取的同名属性;

最后读取parameterType传递的属性,它会覆盖已读取的同名属性。

建议:不要在properties元素体内添加任何属性值,只将属性值定义在properties文件夹中。在properties文件中定义属性名要有一定的特殊性,如xx.xx.x

2、settings

         MyBatis全局配置参数,全局配置参数会影响MyBatis的运行行为。不要随意配置。

3、typeAlias(别名)

         在mapper.xml中,定义很多的statement,statement需要parameterType指定输入参数类型,需要resultType指定输出结果的映射类型。如果在指定类型时输入类型全路径,不方便开发,可针对parameterType 和resultType指定的类型定义一些别名,在mapper.xml中通过别名定义,方便开发。

1)针对单个别名定义(type:类型的路径,alias:别名):

<typeAlias type=”cn.itcast.mybatis.po.User” alias=”user” />

2)批量别名定义(指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写均可)):

<typeAliases>
<package name=”cn.itcast.mybatis.po”/>
</typeAliases>
4、typeHandlers(类处理器)

mybatis中通过typeHandlers完成jdbc类型和java类型的转换。通常情况,mybatis提供的类型处理器满足日常需要,不需要自定义。

5、mappers(映射配置)

1)通过resource加装单个映射文件

<mapper  resource=”mapper/UserMapper.xml”/>

2)通过mapper接口加载

批量加载mapper,指定mapper接口的包名,mybatis自动扫描包下所有mapper接口加载。

遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中。

上边规范的前提是:使用的是mapper代理方法。

<package name=”cn.itcast.mybatis.mapper”/>

动态sql

Mybatis核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。

1、sql示例

<select id=”findUserList” parameterType=”cn.itcast.mybatis.po.UserQueryVo” resultType=”cn.itcast.mybatis.po.UserCustom”>
	SELECT * FROM USER
	<!—where可以自动去掉条件中第一个and -->
	<where>
		<if test=”userCustom!=null”>
			<if test=”userCustom.sex!=null and userCustom.sex!=’’”>
				and user.sex=#{userCustom.sex}
			</if>
			<if text=”userCustom.username!=null and userCustom.username!=’’”>
				and user.username LIKE ‘%${userCustom.username}%’
			</if>
<span style="white-space:pre">		</span></if>
<span style="white-space:pre">	</span></where>
</select>

2、sql片段

定义sql片段:

id:sql片段的唯一标识。

<sql id=”query_user_where”>
	<if test=”userCustom!=null”>
		<if test=”userCustom.sex!=null and userCustom.sex!=’’”>
			and user.sex=#{userCustom.sex}
		<if>
		<if text=”userCustom.username!=null and userCustom.username!=’’”>
			and user.username LIKE ‘%${userCustom.username}%’
		</if>
	</if>
</sql>

经验:1)基于表单来定义sql片段,这样这个sql片段可重用性才高

    2)在sql片段中不要包括where

3、foreach

         向sql传递数组或list,mybatis使用foreach解析。








发布了276 篇原创文章 · 获赞 2 · 访问量 48万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章