#spring整合mybatis
下面是spring整合mybatis的具体步骤,稍不同于官方网站上提供的。
// An highlighted block
var foo = 'bar';
```## 标题
第一步 导入依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>di
</dependency>
第二步 创建配置文件(本来这些配置都是mybatis中的配置,因为spring对mybatis进行的整合,所以这些配置都变得由spring来进行配置,并进行管理,以bean的形式)
**1 创建datasource数据源bean**,
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="wangz1992"/>
</bean>
**将datasource 的beans注入到sqlsessionfactory中,**
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置sqlSession-->
<property name="dataSource" ref="dataSource" />
<!--配置mapperxml映射文件-->
<property name="mapperLocations" value="classpath:UserMapper.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
将sqlsessionfactory注入到sqlsession中,生成sqlsession中,生成对应的sqlsession。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
**第三步 编写实现类**
public class UserDaoImpl implements UserMapper{
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
this.sqlSessionTemplate=sqlSessionTemplate;
}
@Override
public List<User> selectUser() {
UserMapper userMapper=sqlSessionTemplate.getMapper(UserMapper.class);
return userMapper.selectUser();
}
}
**第四步 讲实现类注册到spring中,并将sqlsession注入到该显示类中**
<bean id="UserDaoImpl" class="com.wangz.mapper.UserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
**第五步 编写测试类实现**
@Test
public void testMybatis(){
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("application-config.xml");
UserMapper userMapper= (UserMapper) applicationContext.getBean("UserDaoImpl");
List<User> users=userMapper.selectUser();
for(User user: users){
System.out.println(user);
}
}