MyBatis - one to many - values ​​not set for mapped column

I am using MyBatis to access the database. For this 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 corresponding DAOs look like this:

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

not populated with the correct id. It looks like this is because it is being used as a display column.

Has anyone already experienced this problem or has a solution? Even renaming the columns would not help as far as I can see, because it will still be the displayed column and hence the value will not be set.

I managed to trace it in mybatis code, I think: org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyAutomaticMappings()

only applies mappings for non-mapped columns.

+3


source to share


2 answers


I have found a solution for anyone who might be struggling with the same problem in the future. The weird thing is that you have to specify the id column as an additional result (how it is displayed):



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


source


What I ended up with was to have a separate mapping and method for the parent class with no children. After I got the fully populated object from the mapper, I made a second call to get only the parent class (with the ID) and then just copy the ID into 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());
}

      

0


source







All Articles