2010-11-24 57 views
12

我喜歡用XML表示法來指定全局參數,例如連接字符串。我也喜歡Mapper註釋。當我嘗試將兩者結合時,我得到this exceptionmybatis:將映射器接口與XML配置一起用於全局參數

有沒有辦法將兩者結合?我想爲全局配置使用XML文件,但mybatis會考慮Mapper接口。這個問題是,SqlSessionFactoryBuilder()。build()需要一個Reader(我想用來傳遞XML配置),或者一個配置對象(我看到有addMappers()方法可以幫助我) - 但我不明白如何結合這兩者。

+0

我真的很想知道這個!手動添加映射器接口不是一個合適的解決方案。我們如何配置XML映射器和使用MapperInterfaces而無需手動添加它們? – Chris 2011-05-04 11:47:14

回答

9

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

0

我有同樣的問題,是因爲在MyBatis的映射文件中的名稱空間和映射器接口的包被不匹配。

5

當你創建映射器接口與具有精確方法簽名的抽象方法作爲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);