mybatis使用技巧

1.返回值设置为实体Bean最好,也可以使用hashmap等接收,但不方便。

2.在User.xml可以定义传入类的别名,方便快捷,不需要传入类的全名,使用方式如下:

<typeAlias type="com.someapp.model.User" alias="User"/>

3.通常情况下,mybatis可以自动匹配实体类与数据库表的列名。也可以使用as来使数据库列名与实体类属性名保持一致。

4.可以定义一个ResultMap来接收返回的结果集。主要作用是实体类与数据库表名进行匹配。如下<resultMap id="userResultMap" type="User">

<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
</resultMap>
引用它的语句使用 resultMap 属性就行了(注意我们去掉了 resultType 属性)。比如:

<select id="selectUsers" parameterType="int" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>
5.可以使用sql标签封装部分语句,方便其他地方引用,比如:
<sql id="tbUserColumns">
        user_id as userId,
        user_name as userName,
</sql>

此时就可以在该xml的其他位置引用该sql:

select <include refid="tbUserColumns" />





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis是一款优秀的持久层框架,它支持使用动态SQL语句,灵活地构建SQL语句,使得开发者能够更加方便地实现复杂的业务逻辑。下面介绍一些MyBatis动态SQL使用技巧: 1. if标签 if标签用于判断条件是否成立,从而决定是否拼接SQL语句。if标签的语法如下: ```xml <select id="findUsers" resultType="User"> select * from user <where> <if test="username != null"> and username = #{username} </if> <if test="email != null"> and email = #{email} </if> </where> </select> ``` 上面的代码中,如果传入的username或email不为null,就会拼接相应的SQL语句。这样可以避免拼接过多的无用SQL语句。 2. choose、when、otherwise标签 choose、when、otherwise标签用于实现多重条件判断。当条件成立时,执行对应的SQL语句。choose、when、otherwise标签的语法如下: ```xml <select id="findUsers" resultType="User"> select * from user <where> <choose> <when test="username != null"> and username = #{username} </when> <when test="email != null"> and email = #{email} </when> <otherwise> and 1=1 </otherwise> </choose> </where> </select> ``` 上面的代码中,如果传入的username不为null,就会执行第一个when标签中的SQL语句;如果传入的email不为null,就会执行第二个when标签中的SQL语句;如果传入的username和email都为null,就会执行otherwise标签中的SQL语句。 3. foreach标签 foreach标签用于遍历集合,将集合中的元素拼接成SQL语句。foreach标签的语法如下: ```xml <update id="batchUpdate"> update user set username = #{username}, email = #{email} where id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} </foreach> </update> ``` 上面的代码中,将传入的ids集合中的元素拼接成SQL语句,实现批量更新操作。 4. bind标签 bind标签用于将表达式的值绑定到指定的变量上。bind标签的语法如下: ```xml <select id="findUsers" resultType="User"> <bind name="pattern" value="'%' + username + '%'"/> select * from user where username like #{pattern} </select> ``` 上面的代码中,将传入的username值绑定到pattern变量上,并将pattern变量拼接到SQL语句中,实现模糊查询操作。 以上是MyBatis动态SQL使用的一些技巧,可以帮助开发者更加灵活地构建SQL语句,实现复杂的业务逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值