Notice
Recent Posts
Recent Comments
Link
관리 메뉴

개발자되기 프로젝트

JPA 설정 및 예시 본문

JPA

JPA 설정 및 예시

Seung__ 2021. 5. 23. 00:33

간단하게 HelloWorldController를 만들어서 JPA를 사용해 보도록 하겠음다

 

1. Controller 작성

 


@RestController
//@RequestMapping("/api")
public class HelloWorldController {

    @GetMapping("/hello-world")
    public String helloWorld(){
        return "hello-world";
    }
}

2. ControllerTest 작성


 

@WebMvcTest
class HelloWorldControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void helloWorld() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/hello-world"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string("hello-world"));

    }

}

 

3. User 작성


User class에 @Entity를 붙여 entity로 지정을 한다.

이때 error가 발생한텐데 그 이유는 Entiry 객체는 primary key가 꼭 필요하다.

 

따라서 아래와 같이 id를 만들어 준다.

@Id 가 붙은 property가 entiry 객체의 primary key가 된다.

@GeneratedValue는 primary키의 값증 증가시키는 방법에 대한 spec.을 제공해줌. 하나씩 증가함

@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Data
@Builder
@Entity //Entity에는 primary key가 꼭 필요함.
@EqualsAndHashCode
public class User {

    @NonNull
    private String name;

    @NonNull
    private String email;

    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;

    @Id
    @GeneratedValue //자동으로 하나씩 증가함.
    private Long id;
}

 

4. Repository 생성


그러면 어떻게 entity객체를 저장하고 불러올까? Repository가 필요함

 

JpaRepository를 상속받아  Repository interface를 선언하면 된다.

public interface UserRepository extends JpaRepository<User, Long> {
                                                    //<@Entity 타입, Id 타입>

}

 

4-1.  Repository test 작성


@SpringBootTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void crud(){//create, read, update, delete
        //user객체 생성하고 저장하겠다다
       userRepository.save(new User());
        System.out.println(">>>>"+ userRepository.findAll());

    }

}

JpaRepository에서 제공하는 기능 들.

method 설명
List<TfindAll() 조건 없이 table 전체 값을 리스트로 가져옴
실제 서비스에서는 성능문제 때문에 잘 안씀!
List<TfindAll(Sort sort) findAll()에  정렬 값 추가
List<TfindAllById(Iterable<ID> ids) id를 list형태로 받아서 entity 조회
<S extends T> List<SsaveAll(Iterable<S> entities) entity를 list형식으로 받아서 전부 다 table에 저장
void flush() 현재 jpa context에서 가지고 있는 DB값을 DB에 반영하도록 지시.
<S extends TS saveAndFlush(S entity) 저장한 data를 jpa context에 가지고 있지 말고 바로 DB로 넘겨라
void deleteInBatch(Iterable<T> entities) entity를 list로 받아서 지움.
void deleteAllInBatch() table 전부 다 지움. 잘 쓸 일 없음.
T getOne(ID id) id 값을 가지고 해당 entity 조회
<S extends T> List<SfindAll(Example<S> example) example 활용...?
<S extends T> List<SfindAll(Example<S> example, Sort sort)  

 

'JPA' 카테고리의 다른 글

Repository 제공 기능 2  (0) 2021.05.23
Repository에서 제공하는 기능 예시  (0) 2021.05.23
data.sql작성 및 log조회 방법  (0) 2021.05.23
H2 In-Memory DB  (0) 2021.05.22
JPA 소개  (0) 2021.05.22
Comments