spring boot整合mybatis代码
时间: 2023-09-24 19:06:09 浏览: 99
Spring Boot+Mybatis的整合过程
首先,需要在pom.xml文件中添加Mybatis和Mybatis-Spring的依赖:
```xml
<dependencies>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- Mybatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
```
然后,配置Mybatis的SqlSessionFactory和MapperScannerConfigurer:
```java
@Configuration
@MapperScan("com.example.demo.dao") // 扫描Mapper接口所在的包
public class MybatisConfig {
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("com.example.demo.entity"); // 设置实体类所在的包
return sessionFactory.getObject();
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.example.demo.dao"); // 扫描Mapper接口所在的包
return scannerConfigurer;
}
}
```
其中,`@MapperScan`注解用于指定扫描Mapper接口所在的包,`SqlSessionFactory`用于创建SqlSession,`MapperScannerConfigurer`用于自动扫描Mapper接口并注册到Spring容器中。
最后,编写Mapper接口和Mapper映射文件:
```java
public interface UserMapper {
User selectById(Long id);
}
```
```xml
<mapper namespace="com.example.demo.dao.UserMapper">
<select id="selectById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
这里以查询用户信息为例,使用`@Select`注解或者Mapper映射文件都可以实现。完整的代码可以参考下面的示例:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") Long id) {
return userMapper.selectById(id);
}
}
public interface UserMapper {
User selectById(Long id);
}
<mapper namespace="com.example.demo.dao.UserMapper">
<select id="selectById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
阅读全文