在Spring的核心配置文件中,配置了在指定包下批量扫描mapper映射文件:
<!-- 批量扫描mapper包,创建代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lg.mapper"/> <property name="sqlSessionFactoryBeanName" value="factory"/> </bean>如上所示,spring会扫描com.lg.mapper下的mapper映射文件生成代理对象,它默认扫描的是resources下的com.lg.mapper映射文件,所以你的mapper接口与映射文件要分开写,位置不同,但目录要一致,才能映射到,如:
效果图: mapper接口与映射文件在同一包下,且在都在src/main/java下, 实现步骤: 在之前的指定扫描包的位置下,还需要在pom.xml配置中配置:
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>效果图: mapper接口的目录为com.lg.mapper。 mapper映射文件的目录位置为 resources:mapper/
配置方式:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"> <!-- 使用mybatis:scan 扫描包 --> <mybatis:scan base-package="com.lg.mapper" /> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置mapper文件位置,扫描映射文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"> </property> //..... </bean>