传递参数给 MyBatis @Select

Passing parameter to MyBatis @Select

我正在写我的第一个 MyBatis 应用程序,我一直在@Select。我不知道我的 @Select 定义有什么问题,一切似乎都很好,但我得到了一个 Parameter not found 异常。

当我将参数传递到我的@Insert 语句时,我遵循了相同的模式,并且它没有问题。

我用的是MyBatis 3.4.2.

这是我的@Select:

@Select("SELECT * "
        + "FROM configuration "
        + "WHERE key_name = #{key} AND "
        +       "(#{userId} IS NULL AND user_id IS NULL) OR user_id = #{userId} AND "
        +       "status = 1")
Configuration findByKeyAndUserId(String key, Long userId);

我得到的异常:

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.apache.ibatis.binding.BindingException: Parameter 'key' not found. Available parameters are [arg1, arg0, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'key' not found. Available parameters are [arg1, arg0, param1, param2]

当您传递单个参数对象时,可以通过 getter 或映射的键集直接访问属性。当你想在方法中传递多个参数时,你必须用注解命名参数:

Configuration findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);

这种基于注释的语法实际上表现得像 key-value 映射。密钥由@Param 提供。您为参数变量选择的名称不可见。

请尝试 -parameters 自 JDK 8 以来提供的编译选项。您可以省略 @Param 注释。

https://github.com/mybatis/mybatis-3/issues/549

谢谢。