第一步,引入pom

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.4.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-test</artifactId>
  15. <scope>test</scope>
  16. </dependency>
  17. <!-- springBoot JPA的起步依赖 -->
  18. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-data-jpa</artifactId>
  22. </dependency>
  23. <!-- MySQL连接驱动 -->
  24. <dependency>
  25. <groupId>mysql</groupId>
  26. <artifactId>mysql-connector-java</artifactId>
  27. <version>5.1.35</version>
  28. </dependency>
  29. </dependencies>

第二步,创建User的pojo

数据库
image.png

  1. package com.hikktn.entity;
  2. import javax.persistence.*;
  3. import java.io.Serializable;
  4. /**
  5. * @ClassName UserEntity
  6. * @Description TODO
  7. * @Author lisonglin
  8. * @Date 2021/4/2 15:41
  9. * @Version 1.0
  10. */
  11. @Entity
  12. @Table(name = "user", schema = "test")
  13. public class UserEntity implements Serializable {
  14. @Id
  15. @GeneratedValue(strategy = GenerationType.IDENTITY)
  16. private int id;
  17. private String username;
  18. private String password;
  19. @Id
  20. @Column(name = "id")
  21. public int getId() {
  22. return id;
  23. }
  24. public void setId(int id) {
  25. this.id = id;
  26. }
  27. @Basic
  28. @Column(name = "username")
  29. public String getUsername() {
  30. return username;
  31. }
  32. public void setUsername(String username) {
  33. this.username = username;
  34. }
  35. @Basic
  36. @Column(name = "password")
  37. public String getPassword() {
  38. return password;
  39. }
  40. public void setPassword(String password) {
  41. this.password = password;
  42. }
  43. @Override
  44. public boolean equals(Object o) {
  45. if (this == o) return true;
  46. if (o == null || getClass() != o.getClass()) return false;
  47. UserEntity that = (UserEntity) o;
  48. if (id != that.id) return false;
  49. if (username != null ? !username.equals(that.username) : that.username != null) return false;
  50. if (password != null ? !password.equals(that.password) : that.password != null) return false;
  51. return true;
  52. }
  53. @Override
  54. public int hashCode() {
  55. int result = id;
  56. result = 31 * result + (username != null ? username.hashCode() : 0);
  57. result = 31 * result + (password != null ? password.hashCode() : 0);
  58. return result;
  59. }
  60. @Override
  61. public String toString() {
  62. return "UserEntity{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
  63. }
  64. }

第三步,实现接口

  1. package com.hikktn.repository;
  2. import com.hikktn.entity.UserEntity;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. import java.util.List;
  6. /**
  7. * @ClassName UserRepository
  8. * @Description TODO
  9. * @Author lisonglin
  10. * @Date 2021/4/2 16:00
  11. * @Version 1.0
  12. */
  13. public interface UserRepository extends JpaRepository<UserEntity, Integer>, JpaSpecificationExecutor<UserEntity> {
  14. // 查询全部
  15. List<UserEntity> findAll();
  16. }

第四步,测试

  1. package com.hikktn.test;
  2. import com.hikktn.MySpringBootApplication;
  3. import com.hikktn.entity.UserEntity;
  4. import com.hikktn.repository.UserRepository;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import org.springframework.transaction.annotation.Transactional;
  11. import java.util.List;
  12. import java.util.Optional;
  13. /**
  14. * @ClassName JpaTest
  15. * @Description TODO
  16. * @Author lisonglin
  17. * @Date 2021/4/2 16:02
  18. * @Version 1.0
  19. */
  20. @RunWith(SpringRunner.class)
  21. @SpringBootTest(classes= MySpringBootApplication.class)
  22. public class JpaTest {
  23. @Autowired
  24. private UserRepository userRepository;
  25. @Test
  26. public void testGetUserAll(){
  27. List<UserEntity> users = userRepository.findAll();
  28. System.out.println(users);
  29. }
  30. @Test
  31. public void testAddUser(){
  32. UserEntity userEntity =new UserEntity();
  33. userEntity.setUsername("tom");
  34. userEntity.setPassword("123");
  35. userRepository.save(userEntity);
  36. }
  37. @Test
  38. public void testFindOneUser(){
  39. Optional<UserEntity> byId = userRepository.findById(1);
  40. System.out.println(byId.get());
  41. }
  42. @Test
  43. public void testDeleteUser() {
  44. userRepository.deleteById(5);
  45. }
  46. @Test
  47. @Transactional(rollbackFor = Exception.class)
  48. // @Rollback(value = false)//发生异常不回滚
  49. public void update(){
  50. Optional<UserEntity> optional = userRepository.findById(1);
  51. System.out.println(optional.orElseGet(UserEntity::new));
  52. }
  53. }

第五步,增删改查

  1. package com.hikktn.controller;
  2. import com.hikktn.entity.UserEntity;
  3. import com.hikktn.repository.UserRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.data.domain.Page;
  6. import org.springframework.data.domain.PageRequest;
  7. import org.springframework.web.bind.annotation.*;
  8. import java.util.Optional;
  9. /**
  10. * @ClassName UserController
  11. * @Description TODO
  12. * @Author lisonglin
  13. * @Date 2021/4/2 22:01
  14. * @Version 1.0
  15. */
  16. @RestController
  17. @RequestMapping(path = "/user")
  18. public class UserController {
  19. @Autowired
  20. private UserRepository userRepository;
  21. @GetMapping(path = "/all")
  22. @ResponseBody
  23. public Iterable<UserEntity> getAllUsers(){
  24. return userRepository.findAll();
  25. }
  26. /*
  27. 增加用户
  28. */
  29. @PostMapping()
  30. public UserEntity saveUser(@RequestBody UserEntity user) {
  31. return userRepository.save(user);
  32. }
  33. /*
  34. 删除用户
  35. */
  36. @DeleteMapping("/{id}")
  37. public void deleteUser(@PathVariable("id") int userId) {
  38. userRepository.deleteById(userId);
  39. }
  40. /*
  41. 修改用户
  42. */
  43. @PutMapping("/{id}")
  44. public UserEntity updateUser(@PathVariable("id") int userId, @RequestBody UserEntity user) {
  45. user.setId(userId);
  46. return userRepository.saveAndFlush(user);
  47. }
  48. /*
  49. 查询用户
  50. */
  51. @GetMapping("/{id}")
  52. public UserEntity getUserInfo(@PathVariable("id") int userId) {
  53. Optional<UserEntity> optional = userRepository.findById(userId);
  54. return optional.orElseGet(UserEntity::new);
  55. }
  56. /*
  57. 分页查询多个用户
  58. */
  59. @GetMapping("/list")
  60. public Page<UserEntity> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
  61. @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
  62. return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize));
  63. }
  64. }