springboot+mybatis实现增、删、改、查在idea里怎么用
时间: 2025-04-21 16:06:59 浏览: 27
### 创建 Spring Boot 和 MyBatis 项目
为了在 IntelliJ IDEA 中使用 Spring Boot 和 MyBatis 实现 CRUD 功能,需按照如下方式配置:
#### 配置 `pom.xml` 文件引入所需依赖项
确保项目的 Maven `pom.xml` 文件包含了必要的依赖库来支持 Spring Boot 和 MyBatis 的集成[^5]。
```xml
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis-Spring-Boot-Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL Connector Java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Other dependencies as needed... -->
</dependencies>
```
#### 数据源和 MyBatis 设置
编辑 `src/main/resources/application.properties` 或者 `.yml` 文件以设置数据库连接参数以及指定 MyBatis 映射文件的位置[^3]。
```properties
server.port=8080
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot-crud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
```
#### 启动类定义
修改应用程序的主要入口类(例如 `DemoApplication.java`),通过添加 `@MapperScan` 注解扫描 Mapper 接口所在的包位置[^2]。
```java
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
#### 编写实体类、映射接口和服务层逻辑
对于每一个要管理的数据表,在对应的包下分别创建相应的 Entity 类型、Mapper 接口及其 XML 映射文件。这些组件共同协作完成对特定资源的操作。
##### User.java (Entity)
```java
package com.example.demo.entity;
// 导入所需的包...
@Data // Lombok annotation to reduce boilerplate code.
public class User {
private Long id;
private String name;
private Integer age;
}
```
##### IUserMapper.java (Mapper Interface)
```java
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface IUserMapper {
@Select("SELECT * FROM user WHERE id=#{id}")
User selectById(Long id);
@Insert("INSERT INTO user(name,age) VALUES(#{name}, #{age})")
int insert(User user);
@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
int update(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
int deleteById(Long id);
@Select("SELECT * FROM user")
List<User> findAll();
}
```
##### UserService.java (Service Layer Implementation)
```java
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.IUserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private IUserMapper iUserMapper;
@Override
public User getUserById(Long id){
return this.iUserMapper.selectById(id);
}
@Override
public boolean saveOrUpdateUser(User user){
if(user.getId() != null && this.getUserById(user.getId())!=null){
return this.iUserMapper.update(user)>0;
}else{
return this.iUserMapper.insert(user)>0;
}
}
@Override
public boolean deleteUserById(Long id){
return this.iUserMapper.deleteById(id)>0;
}
@Override
public List<User> getAllUsers(){
return this.iUserMapper.findAll();
}
}
```
#### 控制器编写 RESTful API 方法
最后一步是在控制器中暴露 HTTP 请求处理函数以便外部调用。这里展示了一个简单的例子用于获取单个用户的详情信息[^4]。
```java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{userId}")
public ResponseEntity<User> getUser(@PathVariable(value="userId")Long userId){
User user=this.userService.getUserById(userId);
if(null==user){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(user, HttpStatus.OK);
}
}
```
以上就是完整的基于 IntelliJ IDEA 使用 Spring Boot 结合 MyBatis 完成基本 CRUD 操作的过程描述。这使得开发者能够快速搭建起具有持久化能力的应用程序框架,并利用强大的 ORM 工具简化开发流程。
阅读全文
相关推荐


















