springboot注解形式整合mybatis
时间: 2023-08-24 15:06:04 浏览: 121
SpringBoot整合MyBatis可以简化开发过程,提高开发效率。下面是一个示例,展示如何使用注解形式整合MyBatis:
1. 在pom.xml中添加MyBatis和MyBatis-SpringBoot依赖:
```xml
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
```
2. 在application.properties中添加数据库相关配置:
```
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
```
3. 创建一个Mapper类:
```java
@Mapper
public interface UserMapper {
//查询所有用户
@Select("SELECT * FROM user")
List<User> findAll();
//根据id查询用户
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
//添加用户
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
void insert(User user);
//更新用户
@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
void update(User user);
//删除用户
@Delete("DELETE FROM user WHERE id=#{id}")
void deleteById(@Param("id") Long id);
}
```
4. 在启动类上添加@MapperScan注解:
```java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
5. 在Controller中使用Mapper:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
//查询所有用户
@GetMapping("/users")
public List<User> findAll() {
return userMapper.findAll();
}
//根据id查询用户
@GetMapping("/users/{id}")
public User findById(@PathVariable Long id) {
return userMapper.findById(id);
}
//添加用户
@PostMapping("/users")
public void insert(@RequestBody User user) {
userMapper.insert(user);
}
//更新用户
@PutMapping("/users")
public void update(@RequestBody User user) {
userMapper.update(user);
}
//删除用户
@DeleteMapping("/users/{id}")
public void deleteById(@PathVariable Long id) {
userMapper.deleteById(id);
}
}
```
这样就完成了SpringBoot整合MyBatis的注解形式,可以通过Controller来调用Mapper中的方法来操作数据库。
阅读全文