spring配置实现整合mybatis
时间: 2023-11-27 20:47:49 浏览: 92
实现 Spring 与 MyBatis 的整合,可以通过以下步骤完成:
1.在 pom.xml 文件中添加 MyBatis 和 Spring 的依赖:
```xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
```
2.在 Spring 配置文件中配置数据源和 SqlSessionFactoryBean:
```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/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置 SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.model"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
</bean>
```
3.在 Spring 配置文件中配置 MapperScannerConfigurer:
```xml
<!-- 配置 MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao"/>
</bean>
```
4.在 Dao 的实现类中注入 SqlSessionFactory:
```java
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSessionFactory sqlSessionFactory;
// ...
}
```
阅读全文