温馨提示×

Mybatis的mapper-locations怎么配置

小亿
363
2024-02-01 15:09:38
栏目: 编程语言

在 MyBatis 中,mapper-locations 是用来配置 Mapper 接口的 XML 文件的路径的属性。通过配置 mapper-locations,可以告诉 MyBatis 在哪里找到 Mapper 接口的 XML 文件。

mapper-locations 的配置方式有多种,可以使用相对路径或者绝对路径来指定 XML 文件的位置。下面是一些常见的 mapper-locations 配置示例:

  1. 使用相对路径:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="mapperLocations" value="classpath:com/example/mappers/*.xml" />
    </bean>
    

    上述示例中,mapper-locations 的值为 “classpath:com/example/mappers/*.xml”,表示 Mapper 接口的 XML 文件位于 com/example/mappers 目录下。

  2. 使用绝对路径:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="mapperLocations" value="file:/path/to/mappers/*.xml" />
    </bean>
    

    上述示例中,mapper-locations 的值为 “file:/path/to/mappers/*.xml”,表示 Mapper 接口的 XML 文件位于 /path/to/mappers 目录下。

  3. 使用通配符匹配多个路径:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="mapperLocations" value="classpath:com/example/mappers/*/*.xml" />
    </bean>
    

    上述示例中,mapper-locations 的值为 “classpath:com/example/mappers//.xml”,表示 Mapper 接口的 XML 文件位于 com/example/mappers 目录下的任意一层子目录中。

需要注意的是,mapper-locations 可以配置多个路径,多个路径之间可以使用逗号或者分号分隔。如果有多个路径,MyBatis 会按顺序查找 XML 文件,直到找到为止。

希望以上内容对你有帮助!

0