一. 使用sqlSessionFactory 的 mapperLocations 進行加載,
1
2
3
4
5
6
7
|
<!-- SessionFactory --> <property name= "dataSource" ref= "dataSource" /> <property name= "configLocation" value= "classpath:mybatis-config.xml" /> <!-- 映射文件路徑,可以集中寫到一個地方,也可以與dao寫到一個地方,支持多個路徑,支持通配符--> <property name= "mapperLocations" value= "classpath:mapper/*.xml,classpath:com/sunny/shop/*/dao/*.xml" ></property> </bean> |
此種方法可以使用通配符, 可以指定位置, 可以使用多個位置,
二. 使用MapperScannerConfigurer進行掃描
1
2
3
4
5
|
<!-- 掃描指定包下的所有接口,創建代理類,如果mysql的配置文件名與接口名相同的話,可以不用一一配置 --> <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basePackage" value= "com.sunny.shop" /> <property name= "sqlSessionFactoryBeanName" value= "sqlSessionFactory" ></property> </bean> |
此種方法可以掃描指定包下的接口, 如果需要掃描配置文件, 則配置文件須與對應的DAO接口處于同一目錄, 且名字必須相同
三.配置 mybatis 的 mapper
1
2
3
4
5
6
7
8
|
<mappers> <!-- 既可寫映射文件, 也可寫對應的接口 --> <!--<mapper resource= "com/mybatis/student/StudentMapper.xml" /> <mapper resource= "com/mybatis/classes/ClassesMapper.xml" /> <mapper class = "com.sunny.shop.user.dao.UserDao" /> --> </mappers> |
前兩種都是在spring的配置文件中配置的, 在 mybatis 的配置文件中配置 <mappers>節點
PS:下面給大家介紹下mybatis 加載配置文件的兩種方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package com.atguigu.day03_mybaits.test; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test { public static void test1(){ ///加載mybatis的配置文件(它也加載關聯的映射文件) String str= "conf.xml" ; InputStream is=Test. class .getClassLoader().getResourceAsStream(str); //構建sqlSession的工廠 SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(is); SqlSession session=factory.openSession(); //映射sql的標識字符串,是在影射文件中找到namespace+“”+select中的id String statement= "com.atguigu.day03_mybaits.userMapper.getUser" ; //執行查詢返回一個唯一user對象的sql User user=session.selectOne(statement, 1 ); System.out.println(user); } public static void test2() throws IOException{ ///加載mybatis的配置文件(它也加載關聯的映射文件) String resource = "conf.xml" ; //加載mybatis的配置文件(它也加載關聯的映射文件) Reader reader = Resources.getResourceAsReader(resource); //構建sqlSession的工廠 SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(reader); SqlSession session=factory.openSession(); //映射sql的標識字符串,是在影射文件中找到namespace+“”+select中的id String statement= "com.atguigu.day03_mybaits.userMapper.getUser" ; //執行查詢返回一個唯一user對象的sql User user=session.selectOne(statement, 2 ); System.out.println(user); } public static void main(String[] args) throws IOException { test1(); test2(); } } |
總結
以上所述是小編給大家介紹的mybatis 加載配置文件的方法(兩種方式),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/u011526234/article/details/51202641