Java doesn’t really provide any good means of auto-discovery in this regard, so the best way to do it is to simply tell MyBatis where to find the mapping files.
於是我們有了<mappers>元素:
<!-- 我們可以寫xml檔案的全限定名 --><mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> <mapper resource="org/mybatis/builder/BlogMapper.xml"/> <mapper resource="org/mybatis/builder/PostMapper.xml"/></mappers><!-- 當然也可以是介面路徑 --><mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> <mapper class="org.mybatis.builder.BlogMapper"/> <mapper class="org.mybatis.builder.PostMapper"/></mappers><!-- 這才是最霸道的... --><mappers> <package name="org.mybatis.builder"/></mappers>
如果要把mapper給Spring呢?Scanning for mappers!
我們需要MyBatis-Spring提供的三種方案:
MyBatis-SpringUsing the <mybatis:scan/> element.
<!-- 基本的... --><mybatis:scan base-package="org.mybatis.spring.sample.mapper" />
Using the annotation @MapperScan
//喜歡用註解的...@MapperScan("org.mybatis.spring.sample.mapper")
Using a classic Spring xml file and registering the MapperScannerConfigurer
The MapperScannerConfigurer is a BeanDefinitionRegistryPostProcessor that can be included in a classic xml application context as a normal bean.
<!-- 我最喜歡的 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.mybatis.spring.sample.mapper" /></bean>
然後我再也不需要:
<mappers> <package name="org.mybatis.spring.sample.mapper"/></mappers>
另外,當額外需要定義sqlSessionFactory or sqlSessionTemplate時:
Note bean names are used, not bean references. This is because the scanner loads early during the start process and it is too early to build mybatis object instances.
也就是說:
<!-- 不是ref是value --><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />