Mybatis知识点

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>引用在替换位置即可

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值