zoukankan      html  css  js  c++  java
  • MyBatis 中如何调用 Java 的 enum (枚举) 字段

    事先作成一 enum,如下:

    public enum CityCode {

    ALL("000"),
    BEIJING("010"),
    SHANGHAI("021"),

    private String code;

    CityCode(String code) {
    this.code = code;
    }

    public String val() {
    return this.code;
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    在mapper文件中,想判断一个参数的值是否跟 CityCode.ALL 的值一致的时候,我想当然的像下面这么写了:

    <if test="area != com.test.constant.CityCode.ALL.val" >
    AND
    p.`city`=#{area}
    </if>
    1
    2
    3
    4
    我为什么会这么写?

    因为之前有在 mapper 文件中判断过 List 对象的size 是不是为 0的,就是下面这么写的:

    <if test="statusList.size > 0" >
    // to do sth.
    </if>con
    1
    2
    3
    但是,结果是行,mybatis 报了下面的错:

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'com' not found. Available parameters are [area, param1, param2, now]
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79) ~[mybatis-spring-1.3.0.jar:1.3.0]
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447) ~[mybatis-spring-1.3.0.jar:1.3.0]
    at com.sun.proxy.$Proxy22.selectList(Unknown Source) ~[?:?]
    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:231) ~[mybatis-spring-1.3.0.jar:1.3.0]
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:128) ~[mybatis-3.4.0.jar:3.4.0]
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:68) ~[mybatis-3.4.0.jar:3.4.0]
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53) ~[mybatis-3.4.0.jar:3.4.0]
    at com.sun.proxy.$Proxy38.performance(Unknown Source) ~[?:?]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    后来,又想起来,之前有过在 mybatis 中访问静态方法的示例,试了一下,果然可以,enum 修改如下:

    public enum CityCode {

    ALL("000"),
    BEIJING("010"),
    SHANGHAI("021"),

    private String code;

    CityCode(String code) {
    this.code = code;
    }

    public String val() {
    return this.code;
    }

    public static boolean isAll(String code) {
    return ALL.val().equals(code);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    然后,mapper 文件修改如下:

    <if test="!@com.test.constant.CityCode@isAll(area)" >
    AND
    p.`city`=#{area}
    </if>
    1
    2
    3
    4
    请注意一下语法:
    @xxxxClass@method(parameter)
    我上面那个test部分的第一个 ! 是用来对结果取反的,它不属于语法的一部分。当然,你可以不用 ! 改用 not 也一样的。

  • 相关阅读:
    Oracle配置监听
    Oracle创建表空间和分配用户权限
    Dijkstra
    【刷题】【dp】【记忆化搜索】单词游戏
    【刷题】【记忆化搜索】【dp】Longtail Hedgehog
    【刷题】【dp】 Make The Fence Great Again
    【技巧】【卡常】
    【二分】【基础】(跳石头)(合并果子)(蚯蚓)
    【笔记】两种交换元素的方案对比
    【刷题】【单调栈】请客
  • 原文地址:https://www.cnblogs.com/qianxinxu/p/10713043.html
Copyright © 2011-2022 走看看