如何在另一个映射器中重用MyBatis的映射器?

时间:2018-08-05 09:36:42

标签: java mybatis

我有表eventmessage,它们具有一对一的关系,并由类表示:

public class Event {
    private Long id;
    private Message message;
}

public class Message {
    private Long id;
}

有两个映射器:EventMapperMessageMapper

public interface EventMapper {

    @Select("SELECT * FROM event WHERE date BETWEEN #{from} AND #{to}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "message", column = "message_id",
                    javaType = Message.class, one = @One(select = "getMessage"))
    })
    List<Event> selectInInterval(@Param("from") Date from, @Param("to") Date to);

    @Select("SELECT * FROM message WHERE id = #{id}")
    Message getMessage(@Param("id") Long id);
}


public interface MessageMapper {

    @Select("SELECT * FROM message WHERE id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "text", column = "text")
    })
    List<Event> selectById(@Param("id") Long id);
}

EventMapper选择事件并通过注释将其映射,使用getMessage选择并映射事件的消息。但是我已经在selectById中使用了相同的方法MessageMapper,是否可以重用它?

1 个答案:

答案 0 :(得分:2)

为了使用其他映射器的任何定义(包括语句或ResultMap),您应将映射器的namespace(完全限定名称)包括在该实体的标识符中。

在您的示例中,假设MessageMapper位于com.company.app.mappers软件包中,则为:

public interface EventMapper {

    @Select("SELECT * FROM event WHERE date BETWEEN #{from} AND #{to}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "message", column = "message_id",
                    javaType = Message.class,
                    one = @One(select = "com.company.app.mappers.MessageMapper.getMessage"))
    })
    List<Event> selectInInterval(@Param("from") Date from, @Param("to") Date to);
}