springboot mybatis搭建数据库实现增删改查
时间: 2025-03-07 13:14:12 浏览: 33
### 使用Spring Boot和MyBatis实现CRUD操作
#### 项目依赖配置
在`pom.xml`文件中加入必要的依赖项,确保引入了Spring Boot Starter Web, MyBatis-Spring-Boot-Starter以及H2数据库驱动[^1]。
```xml
<dependencies>
<!-- Other dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
```
#### 配置数据源
通过application.properties或application.yml文件来定义数据源属性。对于H2这样的嵌入式数据库来说,可以指定URL、用户名和密码等信息以便于连接到该数据库实例[^2]。
```yaml
spring:
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MYSQL
driverClassName: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true
```
#### 创建实体类
根据业务需求设计相应的Java对象作为持久化层的数据载体。这里假设有一个名为User的表,则对应的实体类如下所示:
```java
public class User {
private Long id;
private String name;
private Integer age;
// Getters and Setters...
}
```
#### 编写Mapper接口
利用MyBatis提供的特性简化SQL语句映射逻辑。下面是一个简单的例子展示怎样声明一个针对上述User实体的操作方法集合——即DAO(Data Access Object):
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id=#{id}")
User selectById(Long id);
@Insert("INSERT INTO user(name,age) VALUES (#{name}, #{age})")
int insert(User record);
@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
int updateByPrimaryKeySelective(User record);
@Delete("DELETE FROM user WHERE id=#{id}")
int deleteByPrimaryKey(Long id);
}
```
#### Service层封装
为了使控制器能够调用这些底层的方法完成具体的业务处理流程,还需要额外建立一层服务组件负责协调各个模块之间的交互关系。
```java
@Service
public class UserService {
@Autowired
private UserMapper mapper;
public List<User> getAllUsers() {
return mapper.selectList(null);
}
public void addUser(User newUser){
mapper.insert(newUser);
}
public boolean updateUser(User updatedUser){
return mapper.updateById(updatedUser)>0?true:false;
}
public boolean deleteUser(Long userId){
return mapper.deleteById(userId)>0?true:false;
}
}
```
#### 控制器暴露REST API端点
最后一步就是对外提供HTTP请求入口点了,这可以通过创建Controller类并标注@RequestMapping注解的方式达成目的。
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public ResponseEntity<List<User>> list(){
return new ResponseEntity<>(userService.getAllUsers(), HttpStatus.OK);
}
@PostMapping("")
public ResponseEntity<Void> create(@RequestBody User user){
userService.addUser(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Void> edit(@PathVariable long id,@RequestBody User user){
user.setId(id);
if(!userService.updateUser(user)){
throw new ResponseStatusException(HttpStatus.NOT_FOUND,"Unable to find the specified resource");
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> remove(@PathVariable long id){
if (!userService.deleteUser(id)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,"Unable to find the specified resource");
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
```
这样就完成了整个基于Spring Boot与MyBatis框架下简易版用户管理系统的搭建过程,并实现了基本的增删改查功能.
阅读全文
相关推荐


















