Skip to main content
 首页 » 编程设计

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

2024年02月23日53EasonJim

我需要有关 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 使用时间戳字段的类型处理程序。因此,它使用该 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 版本,您可能需要在 @MappedJdbcTypes 注释上设置 includeNullJdbcType=true

参见documentation有关详细信息。