본문 바로가기
Programming/SpringBoot

[Spring Boot] RESTful Service 강의 정리 (15) - JPA Service 구현을 위한 Controller, Repository 생성

by prinha 2020. 8. 27.
반응형

 

 

[Spring Boot] RESTful Service 강의 정리 (14) - Spring Data JPA를 이용한 Entity 설정과 초기 데이터 생성

[Spring Boot] RESTful Service 강의 정리 (13) - JPA 사용을 위한 Dependency, h2 DataBase 추가와 설정 [Spring Boot] RESTful Service 강의 정리 (12) - JPA(Java Persistence API)와 ORM, Hibernate [Spring B..

prinha.tistory.com


Updating GET methods on User Resource to use JPA

 

Spring Data JPA는 일반적인 JPA 기능과는 달리
Entity를 제어하기 위해서 JPA Manager를 사용하지않고 Repository interface를 선언하도록 되어있다.

-> @Repository 선언하는 것만으로 CRUD 기능을 사용할 수 있다.

 

 

1) public interface UserRepository 생성

package com.example.restfulwebservice.user;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
// 데이터베이스에 관련된 bean임을 명시하는 어노테이션
public interface UserRepository extends JpaRepository<User,Integer> {
    // JpaRepository<다룰 Entity의 타입, 기본키의 데이터 타입>

}

 

 - JpaRepository

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.data.jpa.repository;

import java.util.List;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;

@NoRepositoryBean
public interface JpaRepository<T, ID> 
  extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
   
    List<T> findAll();

    List<T> findAll(Sort var1);

    List<T> findAllById(Iterable<ID> var1);

    <S extends T> List<S> saveAll(Iterable<S> var1);

    void flush();

    <S extends T> S saveAndFlush(S var1);

    void deleteInBatch(Iterable<T> var1);

    void deleteAllInBatch();

    T getOne(ID var1);

    <S extends T> List<S> findAll(Example<S> var1);

    <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}

 


2) public class UserJpaController 클래스 생성 -> JpaRepository를 사용

package com.example.restfulwebservice.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/jpa")
public class UserJpaController {

    @Autowired
    private UserRepository userRepository;

    // 전체 사용자 목록을 조회하는 findAll 메소드 사용
    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return userRepository.findAll();
    }
}



 

 

 

 

 

 

반응형