基于MyBatis-plus的SpringBoot开发
以下是一个基于Spring Boot和MyBatis-Plus的简单示例,演示了如何创建一个简单的CRUD应用程序。
- 首先,在
pom.xml
中添加Spring Boot和MyBatis-Plus的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
文件,设置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 创建一个实体类
User
:
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// 省略getter和setter方法
}
- 创建一个Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
// 这里可以添加自定义的数据库操作方法
}
- 创建一个服务类:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
// 在这里可以添加服务层的逻辑
}
- 创建一个控制器类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService)
评论已关闭