当一个项目的mapper中 xml 日益增多的情况下,不可能一个个去手动的注入

  1. <mappers>
  2. <!-- 扫描路径下的mapper映射文件 -->
  3. <mapper resource="mapper/UserMapper.xml"/>
  4. <mapper resource="mapper/UserResultMapper.xml"/>
  5. </mappers>

需要批量注入

1. 原生的方式

把 接口 和 xml 文件放在同一包下

1.1 放在 resources 目录

maven 默认打包会将src/main/java和src/main/resources相同包下的文件合并到同一包中
tips: 本地测试前 maven clean 一下

  1. <mappers>
  2. <package name="com.xxb.mybatisDemon.mapper"/>
  3. </mappers>

image.pngimage.png

1.2 放在 java 目录

如果是 src/main.java 目录下 ,还得配置 maven 的配置文件 因为,如果 xml 文件在 java 目录下,则不会打包。

  1. <build>
  2. <resources>
  3. <resource>
  4. <directory>src/main/java</directory>
  5. <includes>
  6. <include>**/*.xml</include>
  7. </includes>
  8. <filtering>false</filtering>
  9. </resource>
  10. </resources>
  11. </build>

2. 集成 Spring

2.1 使用 XML 进行配置

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
  7. <!-- 配置接口存储的包,用来扫描mapper接口 -->
  8. <mybatis:scan base-package="edu.zju.bme.data.manage.mapper" />
  9. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  10. <!-- 配置mapper文件位置,扫描映射文件,可以使用Ant风格的路径格式 -->
  11. <property name="mapperLocations" value="classpath*:mappers/**/*.xml" />
  12. // ...
  13. </bean>
  14. </beans>