java mybatis:将映射器接口与 XML 配置一起用于全局参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4264485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:35:55  来源:igfitidea点击:

mybatis: Using mapper interfaces with XML config for global parameters

javaormibatismybatis

提问by ripper234

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.

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

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.

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

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.

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

采纳答案by Atilio Ranzuglia

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

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

回答by Achow

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

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

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

例如。这是包含实际查询的 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>

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

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

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

Mybatis-config file

Mybatis 配置文件

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

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

EntityMapperInterface emi = session.getMapper(EntityMapperInterface.class);
List eList = emi.selectEmployeeWithId(1);

回答by Anoop Isaac

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.

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