我正在将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.
``
答案 0 :(得分:1)
发生错误是因为您没有指示mybatis如何将类型Index
的对象转换为存储在student
表中的值(我假设的Index
的ID)。
您需要指定如何从这样的可用对象中获取要存储的值:
@Insert("INSERT INTO student VALUES(#{id}, #{name}, #{index.id})")
int insert(Student student);
答案 1 :(得分:0)
如前所述,我必须将字段放在索引旁边,所以工作代码是
@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);
}