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.
So we have the <mappers> element:
<! -- We can write a fully qualified name for the xml file --> <mappers> <mapper resource = "org/mybatis/builder/AuthorMapper. xml "/> <mapper resource =" org/mybatis/builder/BlogMapper. xml "/> <mapper resource =" org/mybatis/builder/PostMapper. xml "/> </mappers> <! -- Of course, it can also be the interface path --> <mappers> <mapper class = "org. mybatis. builder. authorMapper "/> <mapper class =" org. mybatis. builder. blogMapper "/> <mapper class =" org. mybatis. builder. postMapper "/> </mappers> <! -- This is the most aggressive... --> <mappers> <package name = "org. mybatis. builder"/> </mappers>
What if I want to give mapper to Spring? Scanning for mappers!
We need three solutions provided by MyBatis-Spring:
MyBatis-SpringUsing the <mybatis: scan/> element.
<! -- Basic... --> <mybatis: scan base-package = "org. mybatis. spring. sample. mapper"/>
Using the annotation @ MapperScan
// Annotation like to be used... @ MapperScan ("org. mybatis. spring. sample. mapper ")
Using a classic Spring xml file and registering the MapperScannerConfigurer
The mapperscannerpolicer is a BeanDefinitionRegistryPostProcessor that can be encoded in a classic xml application context as a normal bean.
<! -- My favorite --> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <property name =" basePackage "value =" org. mybatis. spring. sample. mapper "/> </bean>
Then I do not need:
<mappers> <package name="org.mybatis.spring.sample.mapper"/></mappers>
In addition, when you need to define sqlSessionFactory or sqlSessionTemplate:
Note bean names are used, not bean references. This is because the specified loads early during the start process and it is too early to build mybatis object instances.
That is to say:
<! -- Not ref is value --> <property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"/>