本文介绍了MyBatis-一对多-未为映射列设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MyBatis访问数据库.为此,我有以下课程:

I am using MyBatis to access the database.For that purpose I have the following classes:

class ClassA {
    private int id;
    private List<ClassB> list;

    // public getters and setters
}

class ClassB {
    private int id;

    // public getters and setters
}

相应的DAO看起来像这样:

The according DAOs look like that:

public interface ClassADAO {

  @Select("SELECT id, name, description FROM TableA WHERE id = #{id}")
  @Results(
      @Result(property = "list", javaType = List.class, column = "id",
              many = @Many(select = "ClassBDao.getClassBForClassA")))
  ClassA getClassAById(@Param("id") long id);

}

public interface ClassBDAO {

  @Select("SELECT id, classAId FROM TableB WHERE classAId = #{id}")
  ClassB getClassBForClassA(@Param("id") long id);

}

不幸的是, ClassA 的id列未填充正确的ID.看来这是因为它被用作映射列.

Unfortunately the id column of ClassA is not filled with the correct id.It seems that this is because it is used as a mapped column.

有人已经遇到此问题或有解决方案吗?就我所知,即使重命名列也无济于事,因为它仍将是映射的列,因此将不会设置该值.

Anyone already experienced this problem or has a solution? Even renaming of columns would not help as far as I can see it, because it will still be a mapped column and by consequence the value will not be set.

我能够在我认为的mybatis代码中进行跟踪: org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyAutomaticMappings()仅将映射应用于未映射的列.

I was able to track it down in the mybatis code I think:org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyAutomaticMappings() does only apply the mappings for unmapped columns.

推荐答案

我找到了将来可能会遇到相同问题的所有解决方案.奇怪的是,您必须将id列指定为其他结果(因为它已映射):

I found the solution for all that may struggle with the same problem in the future.Strangely you have to specify the id column as additional result (as it is mapped):

public interface ClassADAO {

  @Select("SELECT id, name, description FROM TableA WHERE id = #{id}")
  @Results({@Result(property = "id", column = "id"),
            @Result(property = "list", javaType = List.class, column = "id",
              many = @Many(select = "ClassBDao.getClassBForClassA"))})
  ClassA getClassAById(@Param("id") long id);

}

这篇关于MyBatis-一对多-未为映射列设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:30