Want Mybatis to insert booleans as Y,N, not 0,1

12,961

Solution 1

Modify your insert statement

insert into hello_table (
        is_friendly
    )values (${isFriendly=="0"?"'N'":"'Y'"})

Solution 2

MyBatis typeHandler is a proper way to do it.

You could implement a type handler and then use it in any sql statement:

#{isFriendly, typeHandler=YesNoBooleanTypeHandler}

For the details see MyBatis Java Boolean to Sql enum

Share:
12,961

Related videos on Youtube

mcvkr
Author by

mcvkr

Software engineer, researcher

Updated on September 16, 2022

Comments

  • mcvkr
    mcvkr over 1 year

    I'm writing a class instance to a MySQL DB using MyBatis

    // I have no control over how this java class is laid out -.-
    class Hello {
        boolean isFriendly
    }
    

    my MyBatis Mapper looks like this

    <insert id="doHello" parameterType="Hello">
        insert into hello_table (
            is_friendly   --this is a varchar(1) btw
        )
        values (
          #{isFriendly}
        )
     </insert>
    

    The problem is it inserts the values into the DB as 0 or 1, but I need to have it as 'N' or 'Y' and I don't have the choice of modifying the java

    I'm trying to keep my code as minimal as possible and ideally would like to add stuff into the Mybatis Mapper

    I tried things like

     #{isFriendly,jdbcType=Boolean}
    

    but it didn't work