简体   繁体   中英

Passing parameter to MyBatis @Select

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]

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM