• Spring Boot 整合JPA


    Spring Boot 整合了JPA来访问数据库。在这个示例中,将创建一个简单的实体类User,并使用JPA来进行数据库操作。

    1. 首先,pom.xml
    
        org.springframework.boot
        spring-boot-starter-data-jpa
    
    
        mysql
        mysql-connector-java
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    1. 创建一个实体类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方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. 创建一个JPA Repository接口,继承自JpaRepository,以便进行数据库操作:
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository {
        // 在这里可以添加自定义查询方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 创建一个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 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 updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
            // 查找现有用户
            Optional 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);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    1. 配置application.propertiesapplication.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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 运行应用程序可以看到新建了user表,没有建的话,他会自己建

    2. 并使用浏览器或API测试工具访问/users来执行各种操作,如获取所有用户、获取单个用户、创建用户等。可参考我之前的Idea - Apifox Helper 插件的安装、配置令牌、导出-CSDN博客)

  • 相关阅读:
    Java面向对象编程(进阶)二
    《吐血整理》进阶系列教程-拿捏Fiddler抓包教程(10)-Fiddler如何设置捕获Firefox浏览器的Https会话
    硬件设计——关于Type-C 口的讲解和设计
    《rabbitMQ学习》一 rabbitMQ部署篇
    备战2024秋招面试题-对比Java、Go和Python
    服务器远程桌面经常连接不上,造成远程桌面连接不上的原因都有哪些
    设置visual studio代码自动提示
    MapStruct入门及集成springboot
    【无标题】read out time
    求解 算法 二分归并排序
  • 原文地址:https://blog.csdn.net/qq_43116031/article/details/134297730