MyBatis Spring Boot 自定义类型处理程序

问题描述 投票:0回答:1

我需要 Spring Boot 和 MyBatis 集成方面的帮助。我对自定义 BaseTypeHandler 有疑问。我创建了一个映射器:

@MappedTypes({LocalDateTime.class})
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {

我添加了一个类型处理程序:

sqlSessionFactory.setTypeHandlers(new LocalDateTimeHandler[]{new LocalDateTimeHandler()});

我有下一个错误:

org.apache.ibatis.executor.ExecutorException: No constructor found in com.some.space.SomeObject matching [java.lang.Integer, java.sql.Timestamp, java.sql.Timestamp]

SomeObject 的样子:

public class SomeObject {
    private Long id;
    private LocalDateTime created;
    private LocalDateTime updated;

    public SomeObject(Integer id, LocalDateTime created, LocalDateTime updated){
    //..........
    }
}

我使用 mybatis-spring 和 spring-boot-starter-web 版本 1.3.2。

有关使用 TypeHandler 的所有示例都在 XML 配置上,但我需要使用 Java 配置方式。我做错了什么?


更新:

我的地图绘制者:

@Component
@Mapper
public interface SomeObjectRepository {

    @Select("SELECT * FROM some_objects")
    @Results(value = {
            @Result(property = "created", column = "created_date", typeHandler = LocalDateTimeTypeHandler.class, jdbcType = JdbcType.TIMESTAMP),
            @Result(property = "updated", column = "updated_date", typeHandler = LocalDateTimeTypeHandler.class, jdbcType = JdbcType.TIMESTAMP)
    })
    List<SomeObject> getAll();
}
mybatis spring-mybatis
1个回答
0
投票

您还没有指示 mybatis 使用时间戳字段的类型处理程序。因此,它使用该 JDBC 类型的默认类型处理程序从数据库转换时间戳字段。

如果您只想在某些查询中执行此操作,请对 xml 映射执行以下操作:

<result property="created" column="created"
    typeHandler="com.mycompany.myapp.LocalDateTimeHandler"/>

或者通过注释:

@Result(property = "created", column = "created",
        typeHandler=LocalDateTimeHandler.class)

如果您想使其成为全局并将其用于特定 JDBC 类型的所有字段,请添加

@MappedJdbcTypes
到您
TypeHandler

@MappedJdbcTypes({JdbcType.TIMESTAMP})
@MappedTypes({LocalDateTime.class})
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {

根据您使用的 mybatis 版本,您可能需要在

includeNullJdbcType=true
注释上设置
@MappedJdbcTypes

有关详细信息,请参阅文档

© www.soinside.com 2019 - 2024. All rights reserved.