为什么mybatis不能正确Map一个简单的枚举?

agxfikkp  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(272)

据我所知,我没有做任何不寻常的事。我有一个使用mybatis的spring boot应用程序:

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'

我有一个非常简单的mybatis的application.properties配置:


## MyBatis ##

mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-statement-timeout=30

我的数据库表如下所示:

CREATE TABLE workspace_external_references (
    id CHAR(36) PRIMARY KEY,

    workspace_id CHAR(36) NOT NULL,
    site VARCHAR(255) NOT NULL,
    external_id VARCHAR(255) NOT NULL,

    created_at DATETIME(6) NOT NULL DEFAULT NOW(6),
    updated_at DATETIME(6) NOT NULL DEFAULT NOW(6),

    FOREIGN KEY (workspace_id) REFERENCES workspaces (id) ON DELETE CASCADE
)

只有这样一个条目:

'a907c0af-216a-41e0-b16d-42107a7af05f', 'e99e4ab4-839e-405a-982b-08e00fbfb2d4', 'ABC', '6', '2020-06-09 00:19:20.135822', '2020-06-09 00:19:20.135822'

在我的mapper文件中,我选择了以下所有引用:

@Select("SELECT * FROM workspace_external_references WHERE workspace_id = #{workspaceId}")
List<WorkspaceExternalReference> findByWorkspace(@Param("workspaceId") final UUID workspaceId);

应该Map到的java对象如下所示:

public class WorkspaceExternalReference {
    private UUID id;
    private UUID workspaceId;
    private Sites site;

    private String externalId;

    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;

    public WorkspaceExternalReference(
            final Sites site,
            final UUID workspaceId,
            final String externalId) {
        this.site = site;
        this.workspaceId = workspaceId;
        this.externalId = externalId;
    }
}

public enum Sites {
   ABC, XYZ;
}

为什么这不管用?我得到了这个错误:

Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'id' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant com.acme.Sites.a907c0af-216a-41e0-b16d-42107a7af05f
jxct1oxe

jxct1oxe1#

当没有默认构造函数时,您需要让mybatis知道哪些列要显式传递给构造函数(在大多数情况下)。
对于注解,它将如下所示。
你可以用 <resultMap> 以及 <constructor> 在xmlMap器中。

@ConstructorArgs({
  @Arg(column = "site", javaType = Sites.class),
  @Arg(column = "workspace_id", javaType = UUID.class),
  @Arg(column = "external_id", javaType = String.class)
})
@Select("SELECT * FROM workspace_external_references WHERE workspace_id = #{workspaceId}")
List<WorkspaceExternalReference> findByWorkspace(@Param("workspaceId") final UUID workspaceId);

其他列(即。 id , created_at , updated_at )将通过设置器(如果有)或反射自动Map。
或者,只需将默认(无参数)构造函数添加到 WorkspaceExternalReference 班级。然后在示例化类之后,所有列都将被自动Map。
注意:要使其工作,需要为注册一个类型处理程序 UUID ,但您似乎已经这样做了(否则参数Map将不起作用)。

相关问题