lholloway
lholloway

Reputation: 71

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?

Upvotes: 3

Views: 11525

Answers (3)

lholloway
lholloway

Reputation: 71

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.

Upvotes: 4

jdevelop
jdevelop

Reputation: 12296

Annotate parameter in your interface, like

public interface SomeDao {

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

}

Upvotes: 1

Michał Rybak
Michał Rybak

Reputation: 8706

I assume that with parameterType="Long" MyBatis is treating your parameter like a regular object, not a primitive type or a primitive type wrapper.

MyBatis alias for primitive type long is _long, according to docs.

Try using

<select id="selectTotalRegionCountForGbs" parameterType="_long" resultType="java.lang.Long">

Upvotes: 0

Related Questions