首页 > 解决方案 > 我的巴蒂斯。ResultMap 和属性

问题描述

我正在尝试在我的项目中使用 myBatis。对于“选择”方法,我使用了结果图

    <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="resultMap">
    <resultMap id="userMap" type="db.entities.User">
        <result column="id" property="id"/>
        <result column="login" property="login"/>
        <result column="password" property="password"/>
        <result column="service_profile" property="serviceProfile.id"/>
        <result column="driver_profile" property="driverProfile.id"/>
        <result column="premium_expiring_time" property="premiumExpiringDate"/>
        <result column="registration_date" property="registrationDate"/>
        <result column="last_visit_date" property="lastVisitDate"/>
        <result column="authorization_key" property="authorizationKey"/>
        <result column="last_altitude" property="lastGeoAltitude"/>
        <result column="last_longitude" property="lastGeoLongitude"/>
    </resultMap>
</mapper>

它有效,当我从我的类的函数参数实例中获取时

@ResultMap("resultMap.userMap")
    @Select("SELECT * FROM users WHERE login = #{login} AND password = #{password}")
    fun getUser(user: User): User?

但我认为,这是个坏主意,因为首先我需要创建 User()。当我尝试在函数的参数中使用“登录”和“密码”时,我遇到了一个例外:

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

如何在不创建我的类 User 的实例的情况下使用传入参数?

标签: javakotlinmybatis

解决方案


您需要 1) 添加@Param到每个参数或 2) 添加 Kotlin 编译器选项-java-parameters

1) 如下所示:

@ResultMap("resultMap.userMap")
@Select("SELECT * FROM users WHERE login = #{login} AND password = #{password}")
fun getUser(
  @Param("login") login: String,
  @Param("password") password: String): User?

2) 需要 MyBatis 3.4.1+ 和 Kotlin 1.1+。

MyBatis 的参数名称解​​析有些复杂,主要是因为历史原因。如果您有兴趣,
请参阅此答案。


推荐阅读