溫馨提示×

Mybatis的mapper-locations怎么配置

小億
1074
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 文件,直到找到為止。

希望以上內(nèi)容對你有幫助!

0