MyBatis - 找不到构造函数

MyBatis - No constructor found

MyBatis 映射有问题。 我有一个这样的域 class:

public class MyClass
{
   private Long id;
   private Date create;
   private String content;

   MyClass (Long id, Date create, String content)
   {
       this.id = id;
       this.create = create;
       this.content = content;
   }

   //getters and setters

映射器 class 具有如下方法:

   @Select("SELECT * FROM MyTable WHERE id=#{id}")
   MyClass getMyClass (@Param("id") Long id);

在数据库中,三列的类型为 Number、Timestamp 和 Clob,并且与 class 字段中的名称相同。

当我使用这种方法时,我得到: ExecutorException:在 [MyClass; 中找不到构造函数;匹配 [java.math.BigDecimal, java.sql.Timestamp, oracle.jdbc.OracleClob]

但是如果我从 Myclass 中删除构造函数,那么就完全没有问题。我想要构造函数,我该如何修复它? 我尝试像这样在映射器中添加 @Results 注释,但没有任何区别:

   @Results(value = {
      @Result(column = "id", property = "id", javaType = Long.class),
      @Result(column = "create", property = "create", javaType = Date.class),
      @Result(column = "content", property = "content", javaType = String.class)
   })

MyBatis 期望你的模型对象有一个无参数的构造函数(可能还有每个映射字段的设置器)。添加这些,一切都应该工作。

您可以使用 @ConstructorArgs 代替,如下所示:

@ConstructorArgs({
    @Arg(column = "id", javaType = Long.class)
    ,@Arg(column = "create", javaType = Date.class)
    ,@Arg(column = "content", javaType = String.class)
})

刚刚完成的答案。

如果您想在构造函数中使用原始类型 long 而不是包装器 Long,您需要将绑定更改为:

@ConstructorArgs({
   @Arg(column = "id", javaType = long.class)
   ,@Arg(column = "create", javaType = Date.class)
   ,@Arg(column = "content", javaType = String.class)
})

注意需要在构造函数中添加mybatis @Param注解,以备使用@ConstructorArgs。所以你的构造函数看起来像:

public class MyClass
{
   private long id;
   private Date create;
   private String content;

   MyClass (@Param("id") long id, @Param("create") Date create, @Param("content") String content)
   {
       this.id = id;
       this.create = create;
       this.content = content;
   }

然后你的映射器:

@ConstructorArgs({
   @Arg(name = "id", column = "id", javaType = long.class),
   @Arg(name = "create", column = "create", javaType = Date.class),
   @Arg(name = "content", column = "content", javaType = String.class)
})