SpringBoot 整合 Mybatis
整合步骤:
- 添加依赖:在
pom.xml
中添加Spring Boot Starter和MyBatis的依赖。
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- 数据库驱动,例如MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置数据库和MyBatis:在
application.properties
或application.yml
中配置数据库和MyBatis。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
- 创建Mapper接口和Mapper XML文件。
// UserMapper.java
package com.yourpackage.mapper;
public interface UserMapper {
User selectUserById(int id);
}
<!-- UserMapper.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yourpackage.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.yourpackage.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 创建Service和Controller。
// UserService.java
package com.yourpackage.service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
// UserController.java
package com.yourpackage.controller;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") int id) {
return userService.getUserById(id);
}
}
- 启动类:添加
@SpringBootApplication
注解。
// YourApplication.java
package com.yourpackage;
@Spri
评论已关闭