MyBatis - One to many - values not set for mapped column

*爱你&永不变心* 提交于 2021-02-18 17:40:34

问题


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
}

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

}

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.

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.


回答1:


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

}



回答2:


What I wound up doing was to have a separate mapper and method for the parent class, without the children. After I got the fully-populated object from the mapper, I made a second call to get just the parent class (with the ID), then simply copy the ID to the fully-populated object. Brute force and awkwardness FTW!

ClassA a;    
try (SqlSession session = DBConfig.getSessionFactory().openSession()) {
    ClassAMapper mapper = session.getMapper(ClassAMapper.class);
    a = (mapper.getA(id));
    ClassA a2 = (mapper.getBaseInfo(id));
    a.setID(a2.getID());
}


来源:https://stackoverflow.com/questions/31568779/mybatis-one-to-many-values-not-set-for-mapped-column

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