简体   繁体   English

Spring MyBatis关系映射问题

[英]Spring MyBatis relationship mapping problem

I am using MyBatis with h2 database for learning purposes. 我正在将MyBatis与h2数据库一起用于学习目的。 I have a problem when I want to insert child object inside a parent object in a query, then I got an exception. 当我想在查询的父对象中插入子对象时遇到问题,然后出现异常。

Student class 学生班

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..
}

Index class 索引类别

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..
}

Student repository 学生资料库

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

Index repository 索引库

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

Exception 例外

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.
``

The error happens because you did not instructed mybatis how to convert object of type Index to the value that is stored in student table (the id of the Index I assume). 发生错误是因为您没有指示mybatis如何将Index类型的对象转换为存储在student表中的值(我假设的Index的ID)。

You need to specify how to get the value to be stored from the object that is available like this: 您需要指定如何从可用的对象中获取要存储的值,如下所示:

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

As ave mentioned, I had to put field next to index, so working code is 如前所述,我不得不将字段放在索引旁边,因此工作代码是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM