创建一个基于Spring Boot、MyBatis和Maven的项目可以简化很多配置,因为Spring Boot自带了很多自动配置的功能。下面我将给出一个简单的示例来展示如何搭建这样一个项目。
### 1. 创建一个新的Spring Boot项目
你可以通过Spring Initializr(https://start.spring.io/)来生成项目结构,选择以下依赖:
- Spring Web
- MyBatis Framework
- MySQL Driver (或你使用的数据库驱动)
- Lombok (可选,用于减少样板代码)
或者,直接在IDE中创建一个Spring Boot项目,并手动添加这些依赖。
### 2. Maven `pom.xml` 文件
确保你的`pom.xml`文件中有如下依赖:
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot-mybatis-maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version> <!-- 确保使用最新的稳定版本 -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>17</java.version>
</properties>
<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>3.0.1</version> <!-- 使用最新版本 -->
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok (Optional) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
### 3. 应用程序主类 `Application.java`
创建应用程序入口点:
```java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
### 4. 配置文件 `application.properties`
编辑`src/main/resources/application.properties`以配置数据源和其他属性:
```properties
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.model
# 其他配置...
```
### 5. 创建实体类 `User.java`
```java
package com.example.model;
import lombok.Data;
@Data
public class User {
private Integer id;
private String username;
private String password;
// Getters and Setters (Lombok will handle these)
}
```
### 6. 创建Mapper接口 `UserMapper.java`
```java
package com.example.mapper;
import com.example.model.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(@Param("id") Integer id);
@Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(User user);
@Update("UPDATE users SET username=#{username}, password=#{password} WHERE id=#{id}")
void update(User user);
@Delete("DELETE FROM users WHERE id=#{id}")
void deleteById(@Param("id") Integer id);
@Select("SELECT * FROM users")
List<User> findAll();
}
```
### 7. 创建服务层 `UserService.java`
```java
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void saveOrUpdate(User user) {
if (user.getId() == null) {
userMapper.insert(user);
} else {
userMapper.update(user);
}
}
public void delete(Integer id) {
userMapper.deleteById(id);
}
public User findById(Integer id) {
return userMapper.findById(id);
}
public List<User> findAll() {
return userMapper.findAll();
}
}
```
### 8. 创建控制器 `UserController.java`
```java
package com.example.controller;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> listUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User viewUser(@PathVariable("id") Integer id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
userService.saveOrUpdate(user);
return user;
}
@PutMapping("/{id}")
public User updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
user.setId(id);
userService.saveOrUpdate(user);
return user;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") Integer id) {
userService.delete(id);
}
}
```
### 9. Mapper XML文件(如果需要)
如果你的SQL查询比较复杂,可能需要编写XML映射文件。这些文件应该放在`src/main/resources/mapper/`目录下,并且命名规则应与Mapper接口相匹配,例如`UserMapper.xml`。
```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.example.mapper.UserMapper">
<!-- Example of a complex SQL query -->
<select id="findAll" resultType="com.example.model.User">
SELECT * FROM users
</select>
</mapper>
```
### 注意事项
- 如果你使用了`@Mapper`注解,确保你的Spring Boot应用扫描到了这个注解。
- 确认数据库表结构与实体类字段一致,并检查数据库连接信息是否正确。
- 根据实际情况调整包名、路径以及其他细节。
以上就是一个基本的Spring Boot + MyBatis + Maven项目的搭建过程。希望这个例子能够帮助你开始构建自己的应用程序。如果有任何问题或需要进一步的帮助,请随时提问!