【问题标题】:MyBatis Spring Boot custom type handlerMyBatis Spring Boot 自定义类型处理程序
【发布时间】:2019-04-11 19:42:54
【问题描述】:

我需要有关 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。

关于使用 TypeHandlers 的所有示例都在 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】:

您还没有指示 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

【讨论】:

  • 感谢您的回复。但它在我的情况下不起作用。 MyBatis 尝试使用带有 (Integer, Timestamp, Timestamp) 的构造函数。
  • @AlexLybetsky 摆脱构造函数,只使用公共实例变量。 MyBatis 会找到它们。你不需要二传手。如果您在 JSP 中使用 ${bean.value} 显示对象,则需要 getter。
  • @Roman Konoval 我想为 Timestamp 编写 typeHandler。它应该在全球范围内可见。我做了上面的步骤。 1.写了自己的typeHandler。 2. 添加了 MappedJdbcTypes 和 MappedTypes 注释 3. 在 config.xml 中进行了条目但是对于 Timestamp 数据类型仍然不可见类型处理程序
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2018-08-20
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多