Mast Vinner
Mast Vinner

Reputation: 53

How to map a DB column name that is a Java reserved word to a Java model object field using MyBatis?

So I have a table CoolTable with 2 columns: something and short.

And my model class named CoolClass reflects it with 2 fields: something and _short. short is a Java reserved keyword, so the field had to be prefixed with the underscore.

Now my mybatis mapper XML uses CoolClass like so:

 <select id="getStuff" resultType="CoolClass">
    SELECT * FROM CoolTable
</select>

<insert id = "insertStuff" parameterType = "CoolClass">
    INSERT INTO CoolTable (something, short)
    VALUES (#{something}, #{short})
</insert>

Now, when I getStuff and insertStuff only something column gets retrieved and inserted. short is always null.

I searched through all the MyBatis documentation but couldn't find anything relevant to help with this case.

How can I go about mapping short column to _short field of class?

Upvotes: 0

Views: 485

Answers (1)

Mast Vinner
Mast Vinner

Reputation: 53

Fixed it by using a ResultMap like so:

<resultMap id="coolResultMap" type="CoolClass">
    <result property="_short" column="short"/>
</resultMap>

<select id="getStuff" resultMap="coolResultMap">
    SELECT * FROM CoolTable
</select>

Upvotes: 0

Related Questions