Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyBatis Dynamic SQL using Longs

I'm doing a migration from iBatis to myBatis and during the conversion, I had query that used to work, but now it does not. I've been banging my head against a wall for longer than I'd like to admit trying to get this working.

The query in iBatis was:

<select id="countForACol" parameterClass="java.lang.Long" resultClass="java.lang.Long">
    SELECT
        COUNT(1) AS 'val'
    FROM
        someTable WITH(NOLOCK)
    <isParameterPresent prepend="WHERE">
        someCol = #colId#
    </isParameterPresent>
</select>

Now, I've translated it to a query that looks like this:

<select id="selectTotalRegionCountForGbs" parameterType="Long" resultType="java.lang.Long">
    SELECT
        COUNT(1) AS 'val'
    FROM
        someTable WITH(NOLOCK)
    <where>
        <if test="colId != null">
            someCol = #{colId}
        </if>
    </where>
</select>

This, however, doesn't work. The error I receive when trying to run it is:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'colId' in 'class java.lang.Long'
Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'colId' in 'class java.lang.Long'

I can tell that it is trying to treat the Long object like an object that has a getter called 'getColId' which predictably doesn't exist but I don't know how to signal to MyBatis to use the value of the Long.

How do I get this to work?

like image 678
lholloway Avatar asked Nov 18 '25 11:11

lholloway


2 Answers

I was able to solve the problem by doing this:

<select id="selectTotalRegionCountForGbs" parameterType="Long" resultType="java.lang.Long">
    SELECT
        COUNT(1) AS 'val'
    FROM
        someTable WITH(NOLOCK)
    <where>
        <if test="value != null">
           someCol = #{colId}
        </if>
    </where>
</select>

I changed the test to use "value" instead of "colId" and it worked perfectly.

I believe both @jdevelop and @Michal Rybak's answers would also work.

like image 110
lholloway Avatar answered Nov 21 '25 02:11

lholloway


Annotate parameter in your interface, like

public interface SomeDao {

  Long selectTotalRegionCountForGbs(@Param("colId") long someId);

}
like image 35
jdevelop Avatar answered Nov 21 '25 01:11

jdevelop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!