[springboot/jpa] jpa crud example 1



사용자의 이름과 주소를 관리하는 웹API를 SpringBoot와 Jpa를 이용하여 만들어보겠습니다. 




java 11, gradle 사용


프로젝트 생성 / 라이브러리는 아래와 같이 Lombok, SpringBoot Web, Spring Data Jpa, H2 Database




build.gradle 

plugins {
id 'org.springframework.boot' version '2.3.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}

group = 'com.beans9'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}

test {
useJUnitPlatform()
}


Entity 객체 생성 


Member.java

package com.beans9.jpa.member;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Member {
@Id
@GeneratedValue
Long id;
String name;
String address;

public void update(String name, String address) {
this.name = name;
this.address = address;
}
}


JpaRepository 생성 (interface)


MemberRepo.java

package com.beans9.jpa.member;

import org.springframework.data.jpa.repository.JpaRepository;

public interface MemberRepo extends JpaRepository<Member, Long> {
}


JpaRepository를 사용하는 서비스 클래스 생성 (CRUD)


MemberService.java


package com.beans9.jpa.member;

import java.util.List;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class MemberService {
private final MemberRepo memberRepo;

public List<Member> selectMembers() {
return memberRepo.findAll();
}

public Member getMember(Long id) {
return memberRepo.findById(id).orElseThrow(IllegalArgumentException::new);
}

public Member saveMember(Member member) {
return memberRepo.save(member);
}

public void deleteMember(Long id) {
memberRepo.deleteById(id);
}

@Transactional
public Member updateMember(Long id, Member member) {
Member memberData = memberRepo.findById(id).orElseThrow(IllegalArgumentException::new);
memberData.update(member.getName(), member.getAddress());
return memberData;
}
}


Service를 사용하는 Controller 생성


MemberController.java


package com.beans9.jpa.member;

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/member")
public class MemberController {
private final MemberService memberService;

@GetMapping
public List<Member> selectMembers() {
return memberService.selectMembers();
}

@GetMapping("/{id}")
public Member getMember(@PathVariable Long id) {
return memberService.getMember(id);
}

@PostMapping
public Member saveMember(@RequestBody Member member) {
return memberService.saveMember(member);
}

@PutMapping("/{id}")
public Member updateMember(@PathVariable Long id, @RequestBody Member member) {
return memberService.updateMember(id, member);
}

@DeleteMapping
@ResponseStatus(HttpStatus.OK)
public void deleteMember(@PathVariable Long id) {
memberService.deleteMember(id);
}
}


프로젝트를 실행후에 테스트를 해봅니다. 

Postman을 이용해도 되고 브라우져를 이용해도 됩니다. 전 intellij에 기능인 Http Reqeust를 이용하겠습니다. 


member.http 파일 생성


GET localhost:8080/member

###

POST localhost:8080/member
Content-Type: application/json

{
"name": "c",
"address": "c"
}

###

GET localhost:8080/member/1

###

PUT localhost:8080/member/1
Content-Type: application/json

{
"name": "a_change",
"address": "b_change"
}

###

DELETE localhost:8080/member/1

###


실제 CRUD를 실행해보고 정상적으로 동작하는지 확인해봅니다. 


다음시간에는 지금 소스에서 잘못된 점을 고치면서 좀더 개선해보도록 하겠습니다. 


전체 코드는 아래 깃허브에서 확인가능합니다. 


https://github.com/beans9/springboot-jpa-crud-example