How do configure the dao files to handle inserting a List<String> in MyBatis

可紊 提交于 2019-12-13 03:37:39

问题


I have an object that has a variable that's a List like so:

ExportQueue.java

public class ExportQueue implements Serializable {
    private List<String> errors;

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }
    public void addError(String error) {
        if(this.errors == null) this.errors = new ArrayList<String>();
        this.errors.add(error);
    }
}

I've defined the ResultMap for this...

ExportQueueDao.xml

<mapper namespace="...">
    <resultMap id="exportQueueResultMap" type="...ExportQueue">
         <result property="errors" column="errors"
            typeHandler="...CommaSeparatedStringListTypeHandler" />
    </resultMap>
</mapper>

ExportQueueDao.java

@Insert(INSERT_UPDATE)
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertOrUpdate(ExportQueue ExportQueue);

I have a CommaSeparatedStringListTypeHandler defined but I'm getting an error when I try to INSERT the object. As far as I understand INSERT doesn't use the ResultMap and therefore doesn't see the TypeHander so it doesn't know what to do with the List errors.

This is the error I get with the current set up...

Caused by: org.apache.ibatis.executor.ExecutorException: There was no TypeHandler found for parameter errors of statement ....dao.ExportQueueDao.insertOrUpdate

How do I configure this so MyBatis knows what to do with the List<String> errors?


回答1:


You can define in your myBatis-config to use CommaSeparatedStringListTypeHandler as a default handle for the type List

Once you define this , you wont have to specially mention in the result map the typeHandler for "errors" also while inserting MyBatis will by default use CommaSeparatedStringListTypeHandler for your errors.

<typeHandlers> 
        <typeHandler javaType='List' handler='CommaSeparatedStringListTypeHandler' /> 
</typeHandlers>


来源:https://stackoverflow.com/questions/14762471/how-do-configure-the-dao-files-to-handle-inserting-a-liststring-in-mybatis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!