[Spring Boot]H2+JPA로 DB액세스

한상욱·2023년 11월 5일
0

Spring Boot

목록 보기
5/17
post-thumbnail

들어가며

이 글은 Spring Boot를 공부하며 정리한 글입니다.

CRUD

데이터베이스의 액세스하는 가장 대표적인 4가지는 Create, Read, Update, Delete입니다. 줄여서 CRUD라고 합니다. 이전에는 H2 데이터베이스를 Spring boot 프로젝트에 연결만 해봤다면, 이번에는 Spring boot프로젝트에서 H2 데이터베이스에 CRUD를 수행하는 서버를 만들어보겠습니다.

Repository 만들기

Spring 에서는 Repository를 제공합니다. Repository는 DB에 접근하는 방법을 굉장히 간편하게 구현할 수 있도록 도와주는 추상화 인터페이스에요. 여기서는 간단한 CRUD 예제를 구현할 것이기 때문에 CrudRepository를 이용하겠습니다.

import ...

interface HumanRepository : CrudRepository<Human, Int>

의존성 주입

이제 준비가 완료되었으니, Controller를 만들어보겠습니다.

@RestController
@RequestMapping("/human")
class CoffeeController {

}

Controller에서는 Repository를 이용하기 위해서 humanRepository라는 객체를 생성하여 쉽게 접근할 수 있는데, 이를 의존성 주입 Dependency Injection이라고 합니다. 그리고 이를 수행하기 위한 어노테이션이 @Autowired인데요. 이는 필요한 의존 객체의 타입에 해당하는 빈을 찾아 주입해주는 역할을 합니다.

@RestController
@RequestMapping("/human")
class HumanController {

    @Autowired
    private lateinit var humanRepository : HumanRepository

    @PostConstruct
    private fun loadData() {
        humanRepository.saveAll(
            listOf(
                Human(1, "짱구"),
                Human(2, "맹구"),
                Human(3, "훈이"),
            )
        )
    }
}

추가적으로 초기의 데이터를 임의로 생성하는 loadData 메소드를 생성하였습니다. 이는 @PostConstruct 어노테이션을 이용하여 간단하게 구현할 수 있습니다.

Get 메소드

가장 먼저 만들 메소드는 역시 Get 메소드입니다. 이는 Read에 해당해요.

    @GetMapping
    fun getHumans() = humanRepository.findAll()

Get 메소드는 Repository의 findAll()메소드를 이용하여 쉽게 생성할 수 있습니다.

Post 메소드

Post는 생성입니다. 따라서 Create에 해당해요.

	@PostMapping
    fun postHuman(@RequestBody coffee : Human) = humanRepository.save(coffee)

이 역시 마찬가지로 save메소드를 통해서 아주 간단하게 구현할 수 있습니다.

Put 메소드

이제 수정을 수행해보겠습니다. Update에 해당하겠군요.

    @PutMapping("/{id}")
    fun putHuman(@PathVariable id : Int, @RequestBody coffee : Human) : ResponseEntity<Human> {
        return if (!humanRepository.existsById(id)) ResponseEntity<Human>(humanRepository.save(coffee), HttpStatus.CREATED)
        else ResponseEntity<Human>(humanRepository.save(coffee), HttpStatus.OK)
    }

이 역시 Repository를 이용하면 간단하게 구현됩니다.

Delete 메소드

마지막으로 삭제인 Delete입니다. 이는 CRUD에서도 Delete라고 불립니다.

    @DeleteMapping("/{id}")
    fun deleteHuman(@PathVariable id : Int) = humanRepository.deleteById(id)

deleteById 메소드를 이용해서 간단하게 구현됩니다.

결과확인

이제 결과를 확인할텐데요. Get만 확인하고 나머지는 이후에 다른 글을 통해서 수행해보겠습니다.

profile
자기주도적, 지속 성장하는 모바일앱 개발자가 되기 위해

0개의 댓글