Spring Boot 整合了JPA来访问数据库。在这个示例中,将创建一个简单的实体类User
,并使用JPA来进行数据库操作。
- 首先,
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 创建一个实体类
User
,并使用JPA注解来映射到数据库表:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
// 构造函数、getter和setter方法
}
- 创建一个JPA Repository接口,继承自
JpaRepository
,以便进行数据库操作:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
// 在这里可以添加自定义查询方法
}
- 创建一个Controller类来处理HTTP请求:
import com.lfsun.demolfsunstudyjpa.dao.UserRepository;
import com.lfsun.demolfsunstudyjpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// 获取所有用户
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
// 根据ID获取单个用户
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
// 创建新用户
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
// 根据ID删除用户
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
// 更新用户信息
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
// 查找现有用户
Optional<User> existingUserOptional = userRepository.findById(id);
if (!existingUserOptional.isPresent()) {
// 如果用户不存在,返回404 Not Found响应
return ResponseEntity.notFound().build();
}
User existingUser = existingUserOptional.get();
// 更新用户信息
existingUser.setUsername(updatedUser.getUsername());
existingUser.setEmail(updatedUser.getEmail());
// 保存更新后的用户信息
User savedUser = userRepository.save(existingUser);
// 返回更新后的用户信息和200 OK响应
return ResponseEntity.ok(savedUser);
}
}
- 配置
application.properties
或application.yml
文件以指定数据库连接信息:
spring:
datasource:
url: jdbc:mysql://localhost:3306/study_jpa?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123321
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
-
运行应用程序可以看到新建了user表,没有建的话,他会自己建
-
并使用浏览器或API测试工具访问
/users
来执行各种操作,如获取所有用户、获取单个用户、创建用户等。可参考我之前的Idea - Apifox Helper 插件的安装、配置令牌、导出-CSDN博客)