12

我喜欢用于指定全局参数(例如连接字符串)的 XML 表示法。我也喜欢 Mapper 注释。当我尝试将两者结合起来时,我得到了这个异常

有没有办法将两者结合起来?我想为全局配置使用 XML 文件,但让 mybatis 考虑 Mapper 接口。

问题是 SqlSessionFactoryBuilder().build() 需要一个 Reader(我想用它来传递 XML 配置)或一个 Configuration 对象(我看到它有addMappers()可以帮助我的方法) - 但我没有了解如何将两者结合起来。

4

3 回答 3

10

factory.getConfiguration().addMapper(...);

于 2011-01-06T14:38:10.433 回答
6

当您使用具有与 xml 中的 sql 完全相同的方法签名的抽象方法创建映射器接口时。

例如。这是包含实际查询的 dao.xml 的命名空间。

<mapper namespace=" com.mybatis.dao.EntityMapperInterface">
    <select id="selectEmployeeWithId" parameterType="Long"
        resultType="com.mybatis.domain.Employee">
        select id,name from employee where 1=1
        <if test="_parameter != null"> 
            AND id=#{id} 
        </if>
        order by id
    </select>

会映射到接口 com.mybatis.dao.EntityMapperInterface

public interface EntityMapperInterface {
    public List<Employee> selectEmployeeWithId(Long id);

mybatis-config文件

<mappers>
    <mapper resource="com/mybatis/mappers/EntityMapper.xml" />
</mappers>

你如何从 Action 类/Servlet 中调用它?当你初始化 SqlSession 时,

EntityMapperInterface emi = session.getMapper(EntityMapperInterface.class);
List eList = emi.selectEmployeeWithId(1);
于 2012-03-22T04:39:47.303 回答
0

我有同样的问题,是因为mybatis映射器文件中的命名空间和映射器接口的包不匹配。

于 2011-12-13T20:15:10.497 回答