MyBatis Spring Boot custom type handler

我的未来我决定 提交于 2019-12-10 21:55:25

问题


I need help with Spring Boot and MyBatis integration. I have an issue with custom BaseTypeHandler. I've created a mapper:

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

I've added a type handler:

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

And I have next error:

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

Where SomeObject looks like:

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

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

I using mybatis-spring and spring-boot-starter-web version 1.3.2.

All examples about working with TypeHandlers are on the XML configuration, but I need to use Java configs way. What I'm doing wrong?


UPD:

My mapper:

@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();
}

回答1:


You haven't instructed mybatis to use your type handler for timestamp fields. So it converts timestamp fields from the database using default type handler for that JDBC type.

If you want to do this only in some queries do like this for xml mapping:

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

Or via annotations:

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

If you want to make it global and use it for all fields of the specific JDBC type add @MappedJdbcTypes to you TypeHandler:

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

Depending on the version of mybatis you are using you may need to set includeNullJdbcType=true on the @MappedJdbcTypes annotation.

See documentation for details about this.



来源:https://stackoverflow.com/questions/53205366/mybatis-spring-boot-custom-type-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!