怎么整合spring和mybatis
时间: 2024-05-10 20:14:57 浏览: 96
整合Spring和MyBatis的步骤如下:
1. 在pom.xml文件中添加Spring和MyBatis的依赖项。
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
```
2. 创建数据源和SessionFactory
在Spring配置文件中,需要配置数据源和SessionFactory。
```
<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?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath*:com/example/mapper/*.xml"/>
</bean>
```
3. 配置MapperScannerConfigurer
```
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
```
4. 在Mapper接口上添加@Mapper注解
```
@Mapper
public interface UserMapper {
// ...
}
```
5. 进行测试
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-config.xml"})
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll() {
List<User> userList = userMapper.findAll();
Assert.assertEquals(3, userList.size());
}
}
```
以上就是整合Spring和MyBatis的基本步骤。
阅读全文