Passing parameter to MyBatis @Select

谁都会走 提交于 2019-12-10 22:18:49

问题


I am writing my fist MyBatis application and I stuck around @Select. I do not know what is the problem with my @Select definition, everything seems fine but I got a Parameter not found exception.

I have followed the same pattern when I pass parameters to my my @Insert statement and it works without problem.

I use MyBatis 3.4.2.

This is my @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);

The exception what I got:

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]

回答1:


When you pass a single parameter object, properties are accessed directly through getter or key set for a map. When you want to pass multiple parameters in the method, you have to name the parameters with annotation:

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

This annotation based syntax actually behave like a key-value map. Keys are provided by @Param. The name you choose for parameter variables are not visible.




回答2:


Please try -parameters compile option provided since JDK 8. You can omit a @Param annotation.

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

Thanks.



来源:https://stackoverflow.com/questions/42320837/passing-parameter-to-mybatis-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!