针对给定的pojo类型为myBatis3设计INSERT映射器

时间:2018-10-23 13:33:30

标签: java postgresql mybatis

如果我有类似pojo的模型,myBatis3中的INSERT映射器会如何显示

class DR {
 FormatType format;
}

class SQLDR extends DR{
 String sql;
}

class PDR extends DR {
 Predicate predicate;
}

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

我想在表中插入下载对象,如何在myBatis3中设计INSERT映射器,因为我在运行时设置了SQLDR和PDR类型的下载,因此应该能够根据格式类型取值并进行设置。

我正在尝试这样的映射器,它不起作用

<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>

原因:org.apache.ibatis.reflection.ReflectionException:名称为“ sql”的属性没有吸气剂。在“ DR类”中

1 个答案:

答案 0 :(得分:1)

在这种情况下,最简单的方法是使DR抽象并为其添加方法:

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);
   }
}

然后在没有任何条件的情况下在映射器中使用此新属性:

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