Mybatis知识简记
MyBatis常用配置解析
1)environments标签
数据库环境设置,支持多环境配置
2)mapper标签
加载映射用的,方式如下
- 使用相对于类路径资源引用:
<mapper resource="org/mybatis/xxxMapper.xml">
- 使用全限定资源定位符(URL):
<mapper url="file://org/mybatis/xxxMapper.xml">
- 使用映射器接口实现类的全限定类名:
<mapper class="org.mybatis.xxxMapper.xml">
- 将包内的映射器接口全部注册为映射器:
<package name="org.mybatis.xxxMapper.xml">
3)Properties标签
习惯将数据源的配置信息单独抽取成一个properties文件,该标签用于加载额外的配置的properties文件
4)typeAliases标签
给实体类的全限定类名给别名
<!--起别名前-->
<select id="findAll" resultType="com.tong.pojo.User">
select * from user
</select>
配置typeAliases,为com.tong.pojo.User定义别名user
<typeAliases>
<!--给单独的实体起别名-->
<!-- <typeAlias type="com.tong.pojo.User" alias="user"></typeAlias>-->
<!--批量起别名:该包下所有的类的本身的类名:别名还不区分大小写-->
<package name="com.tong.pojo"/>
</typeAliases>
<select id="findAll" resultType="user">
select * from user
</select>
mybatis框架已经设置好的常用类型别名
mapper.xml之动态Sql语句
if标签:多条件组合
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectUser"></include>
<where>
<if test="id !=null">
and id = #{id}
</if>
<if test="username !=null">
and username = #{username}
</if>
</where>
</select>
当查询条件id和username都存在时控制台打印sql如下:
foreach标签:多值查询
<!--For Example:SELECT * FROM USER WHERE id IN (1,2,5)̶-->
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser"></include>
<where>
<foreach collection="array" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
标签用于遍历集合,其中属性含义如下:
-
collection:代表要遍历的集合,注意编写时不要写#{}
-
open:语句开始部分
-
close:语句结束部分
-
item:遍历集合中的每个元素,生成的变量名
-
separator:分隔符
SQL标签片段抽取:抽取相同的Sql片段,简化编写
<sql id="selectUser" select * from User</sql>
然后使用<include refid="selectUser"></include>
引用在替换位置即可