简体   繁体   中英

Designing INSERT mapper for myBatis3 for given pojo type

How would INSERT mapper in myBatis3 look if i have an pojo model like

class DR {
 FormatType format;
}

class SQLDR extends DR{
 String sql;
}

class PDR extends DR {
 Predicate predicate;
}

class Download {
 DR request;
 String status;
 long size;
}

I want to insert Download object in table, how to design INSERT mapper in myBatis3 as i have downloads of both SQLDR and PDR type set on runtime it should be able to take value based on format type and set it.

I am trying the mapper like this, it does not work

<sql id="DOWNLOAD_FIELD_TYPES">
    #{key,jdbcType=VARCHAR},
    <choose>
        <when test="format = 'SQL'"> #{request.sql,jdbcType=VARCHAR},</when>
        <otherwise> #{request.predicate,jdbcType=VARCHAR}, </otherwise>
    </choose>
    #{status,jdbcType=OTHER},
    #{size,jdbcType=BIGINT},
    #{request.format,jdbcType=OTHER},
</sql>

<sql id="DOWNLOAD_FIELDS">
    key,filter,status,size,format
</sql>

 <insert id="create" parameterType="Download">
    INSERT INTO download(<include refid="DOWNLOAD_FIELDS"/>)
    VALUES(<include refid="DOWNLOAD_FIELD_TYPES"/>)
 </insert>

Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named &apos;sql&apos; in &apos;class DR&apos;

In this case the simplest method would be to make DR abstract and add a method to it:

abstract class DR {
   public String getFilter();
}

class SQLDR {
   String sql;
   public String getFilter() {
       return sql;
   }
}

class PDR {
   Predicate predicate;
   public String getFilter() {
       return toString(predicate);
   }
}

And then use this new property in the mapper without any conditions:

<sql id="DOWNLOAD_FIELD_TYPES">
    #{key,jdbcType=VARCHAR},
    #{request.filter},
    #{status,jdbcType=OTHER},
    #{size,jdbcType=BIGINT},
    #{request.format,jdbcType=OTHER},
</sql>

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