【转载】Mybatis学习笔记【四】

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

作者:niaobirdfly 
来源:CSDN 
原文:https://blog.csdn.net/hellozpc/article/details/80878563 
版权声明:本文为博主原创文章,转载请附上博文链接!

https://blog.csdn.net/zpcandzhj/article/details/80878563

1.Mapper动态代理

使用动态代理,Dao对应的xml文件的namespace要和Dao的全路径一致,所以最好把Dao和它的mapper文件放在同一个包下

2.mybatis-config.xml详解

这里写图片描述

2.1 properties

properties配置的属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。例如:

<properties resource="org/mybatis/example/config.properties">  
    <property name="username" value="dev_user"/>  
    <property name="password" value="F2Fa3!33TYyg"/>
</properties>

然后其中的属性就可以在整个配置文件中被用来替换需要动态配置的属性值。比如:

<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

这个例子中的 username 和 password 将会由 properties 元素中设置的相应值来替换。 driver 和 url 属性将会由 config.properties 文件中对应的值来替换。这样就为配置提供了诸多灵活选择。

属性也可以被传递到 SqlSessionFactoryBuilder.build()方法中。例如:

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props);
// ... or ...
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, props);

如果属性在不只一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:
1)在 properties 元素体内指定的属性首先被读取。
2)然后根据 properties 元素中的 resource 属性读取类路径下属性文件或根据 url 属性指定的路径读取属性文件,并覆盖已读取的同名属性。
3)最后读取作为方法参数传递的属性,并覆盖已读取的同名属性。
因此,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的是 properties 属性中指定的属性。
 

2.2 setting

这里写图片描述

没有开启驼峰匹配:

开启驼峰匹配:

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

2.3 typeAliases

类型别名是为 Java 类型命名的一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。

<typeAliases>
    <typeAlias type="com.zpc.mybatis.pojo.User" alias="User"/>
</typeAliases>

缺点:每个pojo类都要去配置。
解决方案:使用扫描包,扫描指定包下的所有类,扫描之后的别名就是类名(不区分大小写),建议使用的时候和类名一致。

<typeAliases>
    <!--type:实体类的全路径。alias:别名,通常首字母大写-->
    <!--<typeAlias type="com.zpc.mybatis.pojo.User" alias="User"/>-->
    <package name="com.zpc.mybatis.pojo"/>
</typeAliases>

2.4 environments(环境)

MyBatis 可以配置成适应多种环境,例如,开发、测试和生产环境需要有不同的配置;
尽管可以配置多个环境,每个 SqlSessionFactory 实例只能选择其一。
虽然,这种方式也可以做到很方便的分离多个环境,但是实际使用场景下,我们更多的是选择使用spring来管理数据源,来做到环境的分离。

2.5 mappers

告诉 MyBatis 到哪里去找映射文件

可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。例如:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

<!-- 绝对路径 -->
<mappers>
    <mapper url=""/>
</mappers>

这里所谓的mapper接口路径。实际上就是dao的接口路径。在mybatis中,通常把dao的包叫做mapper。类名,也叫做mapper
1、定义一个接口。
2、在接口所在的包中定义mapper.xml,并且要求xml文件和interface的名称要相同。
3、在mybatis-config.xml 中通过class路径,引入mapper。要求mapper.xml 中的名称空间是类的接口的全路径。

3.ResultMap

这里写图片描述

这里写图片描述

这里写图片描述

4. 动态SQL

4.1 where-if

如果想根据性别与名字查找一个人,此时sql语句中会有一个and,即

select * from user sex=#{sex} and name=#{name}

但是不确定这两个信息输入完整,如果错误的信息就过滤掉,只按正确的来查找,那么这个and可能会多余,导致sql语句错误。此时可以使用where-if子句,去掉多余的and

<!-- where标签,可以去掉前and -->
<!-- if标签,判断作用 -->
<select id="SelectByNameAndSex" parameterType="pojo.User" resultType="pojo.User">
	select * from user
	<where>
		<if test="sex!=null and sex==''">
			and sex=#{sex}
		</if>
		<if test="name!=null">
			and name=#{name}
		</if>
	</where>
</select>

4.2 choose when otherwise

场景:查询男性用户,如果输入了姓名则按照姓名模糊查找,否则如果输入了年龄则按照年龄查找,否则查找姓名为“鹏程”的用户。

<select id="queryUserListByNameOrAge" resultType="com.zpc.mybatis.pojo.User">
    select * from tb_user WHERE sex=1
    <!--
    1.一旦有条件成立的when,后续的when则不会执行
    2.当所有的when都不执行时,才会执行otherwise
    -->
    <choose>
        <when test="name!=null and name.trim()!=''">
            and name like '%${name}%'
        </when>
        <when test="age!=null">
            and age = #{age}
        </when>
        <otherwise>
            and name='鹏程'
        </otherwise>
    </choose>
</select>

4.3 where (同上的where-if)

场景:查询所有用户,如果输入了姓名按照姓名进行模糊查询,如果输入年龄,按照年龄进行查询,如果两者都输入,两个条件都要成立

<select id="queryUserListByNameAndAge" resultType="com.zpc.mybatis.pojo.User">
    select * from tb_user
    <!--如果多出一个and,会自动去除,如果缺少and或者多出多个and则会报错-->
    <where>
        <if test="name!=null and name.trim()!=''">
            and name like '%${name}%'
        </if>
        <if test="age!=null">
            and age = #{age}
        </if>
    </where>
</select>

4.4 set

修改用户信息,如果参数user中的某个属性为null,则不修改

<update id="updateUser" parameterType="com.zpc.mybatis.pojo.User">
    UPDATE tb_user
    <trim prefix="set" suffixOverrides=",">
        <if test="userName!=null">user_name = #{userName},</if>
        <if test="password!=null">password = #{password},</if>
        <if test="name!=null">name = #{name},</if>
        <if test="age!=null">age = #{age},</if>
        <if test="sex!=null">sex = #{sex},</if>
        <if test="birthday!=null">birthday = #{birthday},</if>
        updated = now(),
    </trim>
    WHERE
    (id = #{id});
</update>

4.5 foreach

场景:按照多个id查询用户信息

<!-- 等价于select * from tb_user where id in (x1,x2,x3) -->
<!-- 则open为(,close为),separate为, -->
<select id="queryUserListByIds" resultType="com.zpc.mybatis.pojo.User">
    select * from tb_user where id in
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</select>

4.6 总结

If:testognl表达式或者简单java代码
Choose when otherwise—>相当于if else if else
When test参考if
Where,set 都有一定的纠错功能
Trim:prefix suffix prefixOverrides suffixOverrides
Foreach:collection item saparator open close

5.缓存

5.1 一级缓存

这里写图片描述

在mybatis中,一级缓存默认是开启的,并且一直无法关闭

一级缓存满足条件:
1、同一个session中
2、相同的SQL和参数

sqlSession.clearCache();可以强制清除缓存

 

执行update、insert、delete的时候,同样也会清空缓存

5.2 二级缓存

mybatis 的二级缓存的作用域是一个mapper的namespace ,同一个namespace中查询sql可以从缓存中命中。

开启二级缓存:

<mapper namespace="com.zpc.mybatis.dao.UserMapper">
    <cache/>
</mapper>

开启二级缓存,必须序列化: 


public class User implements Serializable{
    private static final long serialVersionUID = -3330851033429007657L;

关闭二级缓存:不开启,或者在全局的mybatis-config.xml 中去关闭二级缓存 

这里写图片描述

<settings>
    <!--开启驼峰匹配-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <!--开启二级缓存,全局总开关,这里关闭,mapper中开启了也没用-->
    <setting name="cacheEnabled" value="false"/>
</settings>

这里写图片描述

 

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

作者:niaobirdfly 
来源:CSDN 
原文:https://blog.csdn.net/hellozpc/article/details/80878563 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值