java - Spring MyBatis关系映射问题

标签 java spring-boot h2 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表中的值(索引 我假设)。

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

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

关于java - Spring MyBatis关系映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620784/

相关文章:

java - 我相信 Eureka 为作为 aws 服务的注册实例生成私有(private)/内部 IP 地址

java - 使用 PKCS11 keystore 类型在 Spring Boot 上的 Web 应用程序中建立 TLS 连接

java - 空结果集上的 Spring Data JPA 聚合函数

Java Sockets - 如果没有客户端尝试连接,则跳过 SocketServeraccept() 方法

java - 获取字符串的特定子串

java - 部署到 Google App Engine 的 Spring Boot (Gradle) 应用程序返回 404 Not Found

sql - H2 数据库是否能够使用聚合函数对 over 子句进行 SQL 查询?

java - H2 未在我的 Spring Boot 应用程序中创建/更新表。我的实体有问题吗?

java - Java的默认访问修饰符曾经是公共(public)的吗

java - 测试 TestNG 中所有包中的所有 JUnit 文件