mybatis xml中定义变量

  • Post author:
  • Post category:其他


前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。

点击跳转到网站。

mybatis定义全局变量只需要配置一下即可,那如何在mybatis xml文件中定义局部变量呢?这就需要使用

<bind>

标签了。


bind

标签允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。通俗来讲它就是声明了一个局部变量,它的优先级是高于其他语句的。

格式:

<bind name="name" value="value"/>
  • name:定义的变量名称
  • value:value是一个具体的值,它可以是入参,也可以是一个表达式,比如:判断条件



举例

UserInfo实体类

public class UserInfo {
    private Long id;
    private String gender;
    private String name;
    private Date createDate;
}

不使用

bind

标签的SQL语句

<select id="bindTest" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from users
    <where>
        <choose>
            <when test="minId != null and minId > 0 and maxId != null and maxId > 0">
                and id between #{minId} and #{maxId}
            </when>
            <otherwise>
                <if test="minId != null and minId > 0">
                    and id &gt;= #{minId}
                </if>
            </otherwise>
        </choose>
        <if test="username != null and username.trim() != ''">
            and name like concat('%' , #{username} , '%')
        </if>
    </where>
</select>

测试类

@Test
public void testBind(){
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
    List<UserInfo> userInfos = userInfoMapper.bindTest(1L , 10L, "0");
    System.out.println(userInfos);
}

运行测试类,打印的SQL语句:

sql=select Id, gender , name , create_date from users WHERE id between 1 and 10 and name like concat('%' , '0' , '%')

修改成使用

bind

标签的SQL语句:

<select id="bindTest" resultMap="BaseResultMap">
   <bind name="minIdFlag" value="minId != null and minId > 0"/>
    <bind name="maxIdFlag" value="maxId != null and maxId > 0"/>
    <bind name="usernameLike" value="'%' + username + '%'"/>
    
    select
    <include refid="Base_Column_List" />
    from users
    <where>
        <choose>
            <when test="minIdFlag and maxIdFlag">
                and id between #{minId} and #{maxId}
            </when>
            <otherwise>
                <if test="minIdFlag">
                    and id &gt;= #{minId}
                </if>
            </otherwise>
        </choose>
        <if test="username != null and username.trim() != ''">
            and name like #{usernameLike}
        </if>
    </where>
</select>

运行测试类,打印SQL如下:

sql=select Id, gender , name , create_date from users WHERE id between 1 and 10 and name like '%0%'

对比一下可以发现使用

<bind>

标签前后的sql语句都是一样的,也说明

<bind>

标签替换成功。



注意事项


  • bind

    标签的value不能为null

  • bind

    标签name最好不要使用点

    ·

    进行赋值操作,如果使用的话直接取值是没问题的, 但是如果在

    <if>



    <when>

    等标签中使用时会报

    no getter xx

    异常。

本篇简单介绍了一下

<bind>

标签的使用,希望对你有用。



版权声明:本文为qq_39654841原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。