spring跟mybatis整合方式
时间: 2023-07-12 12:35:28 浏览: 210
Spring和MyBatis的整合方式可以通过以下步骤实现:
1. 添加MyBatis和Spring的依赖:
```xml
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
```
2. 配置数据源:
```xml
<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" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
```
3. 配置MyBatis的SqlSessionFactory:
```xml
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
```
4. 配置MyBatis的MapperScannerConfigurer:
```xml
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao" />
</bean>
```
5. 创建一个MyBatis的Mapper接口:
```java
public interface UserMapper {
User getUserById(int id);
}
```
6. 在Spring中注入Mapper接口:
```xml
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.example.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
```
7. 在代码中使用Mapper接口:
```java
@Autowired
private UserMapper userMapper;
```
这样,Spring和MyBatis就整合好了,可以愉快地进行数据库操作了。
阅读全文