春季MyBatis关系映射问题



我正在使用 MyBatis 和 h2 数据库进行学习。当我想在查询的父对象内插入子对象时,我遇到了问题,然后我遇到了异常。

学生班

public class Student {
  private Long id;
  private String name;
  private Index index;
  public Student(Long id, String name, Index index) {
    this.id = id;
    this.name = name;
    this.index = index;
  }
// getters and setters..
}

索引类

public class Index {
  private Long id;
  private String number;
  public Index() { }
  public Index(Long id, String number) {
    this.id = id;
    this.number = number;
  }
// getters and setters..
}

学生存储库

@Mapper
@Repository
public interface StudentRepo {
  @Select("SELECT * FROM student WHERE id=#{id}")
  Student findById(long id);
                 // exception occurs for index field, which is my child object
  @Insert("INSERT INTO student VALUES(#{id}, #{name}, #{index})")
  int insert(Student student);
}

索引存储库

@Mapper
@Repository
public interface IndexRepo {
  @Select("SELECT * FROM index WHERE id =#{id}")
  Index findById(long id);
  @Insert("INSERT INTO index VALUES(#{id}, #{number})")
  int insert(Index index);
}

例外

Caused by: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'index'. It was either not specified and/or could not be found for the javaType (com.example.batis.domain.Index) : jdbcType (null) combination.
``

发生错误是因为您没有指示 mybatis 如何将 Index 类型的对象转换为存储在student表中的值(我假设Index的 id(。

您需要指定如何从可用的对象中获取要存储的值,如下所示:

@Insert("INSERT INTO student VALUES(#{id}, #{name}, #{index.id})")
int insert(Student student);

正如 ave 提到的,我不得不在索引旁边放置字段,所以工作代码是

@Mapper
@Repository
public interface StudentRepo {
  @Select("SELECT * FROM student WHERE id=#{id}")
  Student findById(long id);
  @Insert("INSERT INTO student VALUES(#{id}, #{name}, #{index.id})")
  int insert(Student student);
}

最新更新