以下是一个Spring Boot整合MyBatis Plus和MySQL的示例:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Plus Starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.x.x</version> <!-- 替换为实际版本号 -->
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Test Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
文件:
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.mapper-locations=classpath:/mappers/**/*.xml
mybatis-plus.type-aliases-package=com.yourpackage.model
- 创建实体类和Mapper接口:
// User.java (实体类)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
// UserMapper.java (Mapper接口)
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 这里可以添加自定义方法
}
- 创建Service层和Controller层:
// UserService.java (Service层)
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.selectList(null);
}
}
// UserController.java (Controller层)
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/")
public List<User> getAllUsers() {
return userService.get