[REST API] JPA와 Hibernate로 H2 db와 REST API 연결시키기

민지·2024년 3월 18일
0

REST API - Spring Boot

목록 보기
24/27

UserResource 컨트롤러가 데이터베이스와 소통하게 하려면, JpaRepository 인터페이스를 extends하는 UserRepository를 만들어야 한다!

1. UserRepository

restfulwebservices/jpa/UserRepository.java New

package com.minjiki2.rest.webservices.restfulwebservices.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import com.minjiki2.rest.webservices.restfulwebservices.user.User;

public interface UserRepository extends JpaRepository<User, Integer> {

}

그럼 이제 실제로 데이터베이스와 소통하는 기능을 적을, UserResource코드를 update시키자! -> UserResource를 복사해, UserJpaResource로 rename시킨다!

2. UserJpaResource

retrieveAllUsers() 메소드 → service 멤버변수를 repository로 수정

@RestController
public class UserResourceJpa {

	private UserRepository repository;

	@Autowired
	public UserResourceJpa(UserRepository repository) {
		super();
		this.repository = repository;
	}

	// GET /users
	@GetMapping("/jpa/users")
	public List<User> retrieveAllUsers() {
		return repository.findAll();
	}

}

실행결과,

retrieveOneUser 메서드 수정

  • service 멤버변수 → repository 멤버변수 수정
  • repository의 멤버함수 findById의 리턴값이 Optional<T>라서, .get메서드를 이용해 user값을 받아오게 수정했다.
	@GetMapping("/jpa/users/{id}")
	public EntityModel<User> retrieveOneUser(@PathVariable("id") int id) {
		User user = repository.findById(id).get();

		if (user == null) {
			throw new UserNotFoundException("id" + id);
		}

		EntityModel<User> entityModel = EntityModel.of(user);

		WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers());
		entityModel.add(link.withRel("all-Users"));

		return entityModel;
	}

deleteUser 메서드 수정

  • service 멤버변수 → repository 멤버변수만 수정
// DELETE /users/{id}
@DeleteMapping("/jpa/users/{id}")
public void deleteUser(@PathVariable("id") int id) {
	repository.deleteById(id);
}

CreateUser 메서드 수정

  • service 멤버변수 → repository 멤버변수만 수정
// POST /users
@PostMapping("/jpa/users")
public ResponseEntity<User> CreateUser(@Valid @RequestBody User user) {

	User savedUser = repository.save(user);
	// /users/4 => /users/{id}, user.getID
	URI location = ServletUriComponentsBuilder.fromCurrentContextPath()

			.path("/{id}").buildAndExpand(savedUser.getId()).toUri();

	return ResponseEntity.created(location).build();
}



사진 크기 상 전체화면은 아니지만,, 잘 올라온 것을 알 수 있다!



참고 및 출처

이 시리즈는 Udemy 강의의 내용을 정리한 것입니다.
https://www.udemy.com/course/spring-boot-and-spring-framework-korean/

profile
배운 내용을 바로바로 기록하자!

0개의 댓글