随笔 - 1162  文章 - 0  评论 - 16  阅读 - 59万 

Mapper 体系结构

自定义接口

1、自定义接口用途

可以根据开发的实际需要对Mapper 接口进行定制

如果你想按需选择接口,不想使用Mapper包含的那么多的方法,你可以创建自己的MyMapper,自己搭配想要的方法。

2、创建自定义MyMapper 接口

3、配置自定义接口

配置MapperScanConfiguration 注册 MyMapper

    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.njf.mapper.mappers"/>
        <property name="properties">
            <value>
                mappers=com.njf.mapper.customized_mapper.MyMapper
            </value>
        </property>
    </bean>

如果我自己定义了MyMapper,MyMapper2,MyMapper3,可以如下配置:

<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.isea533.mybatis.mapper"/>
    <property name="properties">
        <value>
            mappers=com.xxx.xxx.MyMapper,com.xxx.xxx.MyMapper2,com.xxx.xxx.MyMapper3
        </value>
    </property>
</bean>

如果你觉得配置太长不方法,你可以这样:

public interface AllMapper<Textends
    MyMapper<T>,
    MyMapper2<T>,
    MyMapper3<T> {

}

然后配置mappers=com.xxx.xxx.AllMapper即可。

4、测试自定义Mapper接口

public class MyMapperTest {

    private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
    private EmployeeService employeeService = ioc.getBean(EmployeeService.class);

    @Test
    public void test() {
        List<Employee> emp = employeeService.getAll();
        emp.forEach(System.out::println);
    }
}


@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    public List<Employee> getAll() {
        return employeeMapper.selectAll();
    }
}

运行结果:

可以看到数据成功查出。

5、易错点

(1)自定义接口与要使用的Mapper接口不能放在同一个包中。

posted on   格物致知_Tony  阅读(268)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示

目录导航