springboot+mybatis项目框架的搭建
时间: 2023-10-05 07:11:22 浏览: 39
搭建 Spring Boot 和 MyBatis 项目框架需要以下步骤:
1. 创建一个 Spring Boot 项目,可以使用 Spring Initializr 或者在 IDE 中创建项目。
2. 添加 MyBatis 和 MySQL 的依赖。可以在 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
```
3. 配置数据源。在 application.properties 文件中添加以下配置:
```
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
4. 创建实体类和 Mapper 接口。实体类用于映射数据库中的表,Mapper 接口用于定义 SQL 操作。例如:
```
public class User {
private Long id;
private String name;
private Integer age;
// getter and setter
}
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
void save(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void deleteById(Long id);
}
```
5. 在 Spring Boot 主类中添加 @MapperScan 注解,指定 Mapper 接口所在的包。
```
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
6. 在 Controller 中使用 Mapper 接口进行操作。例如:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userMapper.findById(id);
}
@PostMapping("/")
public void save(@RequestBody User user) {
userMapper.save(user);
}
@PutMapping("/{id}")
public void update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userMapper.update(user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
userMapper.deleteById(id);
}
}
```
这样就完成了 Spring Boot 和 MyBatis 项目框架的搭建。