简体   繁体   中英

myBatis. ResultMap and properties

I am trying to use myBatis in my project. For the "Select" method, I used result map

    <?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>

And it works, when I get from my function's argument instance of my class

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

But I think, that it is bad idea, because first I need to create User(). When I try to use "login" and "password" in function's arguments, I take an exception:

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]

How can I use incoming arguments without creating instance of my class User?

You need to 1) add @Param to each parameter or 2) add Kotlin compiler option -java-parameters .

1) would look as follows:

@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) requires MyBatis 3.4.1+ and Kotlin 1.1+.

MyBatis' parameter name resolution is somewhat complicated mainly because of historical reasons.
See this answer if you are interested.

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