12

I like the XML notation for specifying global parameters such as connection strings. I also like Mapper annotations. When I try to combine the two, I get this exception.

Is there a way to combine the two? I would like to use an XML file for the global configurations, but have mybatis take Mapper interfaces into account.

The problem is that SqlSessionFactoryBuilder().build() takes either a Reader (which I want to use to pass the XML config), or a Configuration object (which I see has the addMappers() method that can help me) - but I don't understand how to combine the two.

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • I'd really like to know this! Adding the mapper Interfaces by hand isn't a suitable solution. How can we configure mappers in XML and using MapperInterfaces together without adding them by hand? – Chris May 04 '11 at 11:47

4 Answers4

10

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

Dariusz
  • 21,561
  • 9
  • 74
  • 114
6

When u create the mapper interface with the abstract methods having the exact method signature as the sql in the xml.

For eg. This was the namespace for the dao.xml which contained the actual query.

<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>

It will be mapped in the interface com.mybatis.dao.EntityMapperInterface

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

Mybatis-config file

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

How do u call it from the Action class/Servlet? When u have the SqlSession initialized,

EntityMapperInterface emi = session.getMapper(EntityMapperInterface.class);
List eList = emi.selectEmployeeWithId(1);
Achow
  • 8,600
  • 6
  • 39
  • 49
0

Thanks, It helps me a lot. I use no XML config mybatis with spring. Here's what I do:

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
Configuration configuration = new Configuration();
configuration.addMapper(AccountMapper.class);
factoryBean.setConfiguration(configuration);
return factoryBean.getObject();
quentinLi
  • 1
  • 1
0

I had the same issue and was because the name space in mybatis mapper file and the package of the mapper interface were not matching.

Anoop Isaac
  • 932
  • 12
  • 15