一、准备工作:
1.1 添加相应的jar包依赖:
这里用到了两个jar包,一个是mybatis的,另一个是mybatis-spring的,代码如下:
1
2
3
4
5
6
7
8
9
10
|
< dependency >
< groupId >org.mybatis</ groupId >
< artifactId >mybatis</ artifactId >
< version >3.2.2</ version >
</ dependency >
< dependency >
< groupId >org.mybatis</ groupId >
< artifactId >mybatis-spring</ artifactId >
< version >1.1.1</ version >
</ dependency >
|
1.2 spring中配置mybatis
要想在spring中使用mybatis,需要在spring的上下文中配置两个内容:SqlSessionFactory和至少一个数据映射器。SqlSessionFactory使用mybatis-spring包中的SqlSessionFactoryBean,使用SqlSessionTemplete实现SqlSession接口。代码如下:
1
2
3
4
5
6
7
|
< bean id = "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" >
< constructor-arg index = "0" ref = "sqlSessionFactory" />
</ bean >
< bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" >
< property name = "configLocation" value = "classpath:/mybatis/mapperConfig.xml" ></ property >
< property name = "dataSource" ref = "dataSource" />
</ bean >
|
需要注意的是,SqlSessionFactory需要dataSource。