Java, IntelliJ/Spring

Spring_CRUD할 수 있는 API 연습

고로케 2021. 6. 27.
반응형

 

1-1. application.properties 설정

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.show-sql=true

 

1-2. Application 에 JPA 실행코드 작성

# main 아래에 삽입    
    @Bean
    public CommandLineRunner demo(PersonRepository repository) {
        return (args) -> {
            repository.save(new Person("엉덩이","스프링개발자",30,"방구석"));
        };
    }

 

 

2-1. domain 패키지 -> Person.java 클래스 생성

person에 필요한 객체들 선언

@Getter
@NoArgsConstructor
@Entity
public class Person {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String job;

    @Column(nullable = false)
    private int age;

    @Column(nullable = false)
    private String address;
    }
    
    public Person(String name, String job, int age, String address) {
    this.name = name;
    this.job = job;
    this.age = age;
    this.address = address;
    }

 

2-2. domain 패키지 -> PersonRepository 인터페이스 생성

public interface PersonRepository extends JpaRepository<Person, Long> {
}

 

2-3 domain 패키지 -> TimeStamped. java 생성

@MappedSuperclass // 상속했을 때, 컬럼으로 인식하게 합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/수정 시간을 자동으로 반영하도록 설정
public class Timestamped {

    @CreatedDate // 생성일자임을 나타냅니다.
    private LocalDateTime createdAt;

    @LastModifiedDate // 마지막 수정일자임을 나타냅니다.
    private LocalDateTime modifiedAt;
}

-> Person.java 클래스 옆에 extends TimeStamped 추가

public class Person extends Timestamped {

-> Application 클래스 위에 @EnableJpaAuditing 

-> Application repository.save 구문 작성

@EnableJpaAuditing
@SpringBootApplication
public class Homework2Application {
    public static void main(String[] args) {
        SpringApplication.run(Homework2Application.class, args);
        }

# main 아래에 삽입    
    @Bean
    public CommandLineRunner demo(PersonRepository repository) {
        return (args) -> {
            repository.save(new Person("엉덩이","스프링개발자",30,"방구석"));
        };
}

 

여기까지 결과

 


 

완성본

1. controller 패키지-PersonController.java

package com.homework2.homework2.controller;

import com.homework2.homework2.domain.Person;
import com.homework2.homework2.domain.PersonRepository;
import com.homework2.homework2.domain.PersonRequestDto;
import com.homework2.homework2.service.PersonService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@RestController
public class PersonController {

    private final PersonService personService;
    private final PersonRepository personRepository;

    @GetMapping("/api/persons")
    public List<Person> getPersons() {
        return personRepository.findAll();
    }

    @PostMapping("/api/persons")
    public Person createPerson(@RequestBody PersonRequestDto requestDto) {
        Person person = new Person(requestDto);
        return personRepository.save(person);
    }

    @PutMapping("/api/persons/{id}")
    public Long updatePerson(@PathVariable Long id, @RequestBody PersonRequestDto requestDto) {
        return personService.update(id, requestDto);
    }

    @DeleteMapping("/api/persons/{id}")
    public Long deletePerson(@PathVariable Long id) {
        personRepository.deleteById(id);
        return id;
    }
}

2. domain 패키지

1) Person.java

package com.homework2.homework2.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Getter
@NoArgsConstructor
@Entity
public class Person extends TimeStamped {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String job;

    @Column(nullable = false)
    private int age;

    @Column(nullable = false)
    private String address;


    public Person(PersonRequestDto requestDto) {
        this.name = requestDto.getName();
        this.job = requestDto.getJob();
        this.age = requestDto.getAge();
        this.address = requestDto.getAddress();
    }
    public Person(String name, String job, int age, String address) {
        this.name = name;
        this.job = job;
        this.age = age;
        this.address = address;
    }

    public void update(PersonRequestDto requestDto) {
        this.name = requestDto.getName();
        this.job = requestDto.getJob();
        this.age = requestDto.getAge();
        this.address = requestDto.getAddress();
    }

}

2) PersonRepository 인터페이스

package com.homework2.homework2.domain;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<Person, Long> {
}

3) PersonRequestDto.java

package com.homework2.homework2.domain;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@RequiredArgsConstructor
public class PersonRequestDto {
    private final String name;
    private final String job;
    private final int age;
    private final String address;

}

3) TimeStamped.java

package com.homework2.homework2.domain;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;



@MappedSuperclass // 상속했을 때, 컬럼으로 인식하게 합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/수정 시간을 자동으로 반영하도록 설정
public class TimeStamped {

    @CreatedDate // 생성일자임을 나타냅니다.
    private LocalDateTime createdAt;

    @LastModifiedDate // 마지막 수정일자임을 나타냅니다.
    private LocalDateTime modifiedAt;
}

3. Service 패키지 - PesonService.java

package com.homework2.homework2.service;

import com.homework2.homework2.domain.Person;
import com.homework2.homework2.domain.PersonRepository;
import com.homework2.homework2.domain.PersonRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@RequiredArgsConstructor
@Service
public class PersonService {
    private final PersonRepository personRepository;

    @Transactional
    public Long update(Long id, PersonRequestDto requestDto) {
        Person person = personRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 id가 존재하지 않습니다.")
        );
        person.update(requestDto);
        return person.getId();
    }
}

4. Application

package com.homework2.homework2;

import com.homework2.homework2.domain.Person;
import com.homework2.homework2.domain.PersonRepository;
import com.homework2.homework2.domain.PersonRequestDto;
import com.homework2.homework2.service.PersonService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.util.List;

@EnableJpaAuditing
@SpringBootApplication
public class Homework2Application {

    public static void main(String[] args) {
        SpringApplication.run(Homework2Application.class, args);
    }

    @Bean
    public CommandLineRunner demo(PersonRepository personRepository, PersonService personService) {
        return (args) -> {
            personRepository.save(new Person("엉덩이", "스프링 개발자", 25, "허리 아래"));

            System.out.println("데이터 인쇄");
            List<Person> personList = personRepository.findAll();
            for (int i = 0; i < personList.size(); i++) {
                Person person = personList.get(i);
                System.out.println(person.getId());
                System.out.println(person.getName());
                System.out.println(person.getJob());
                System.out.println(person.getAge());
                System.out.println(person.getAddress());
            }

            PersonRequestDto requestDto = new PersonRequestDto("정수리", "노드 개발자", 26, "머리 꼭대기");
            personService.update(1L, requestDto);
            personList = personRepository.findAll();
            for (int i = 0; i < personList.size(); i++) {
                Person person = personList.get(i);
                System.out.println(person.getId());
                System.out.println(person.getName());
                System.out.println(person.getJob());
                System.out.println(person.getAge());
                System.out.println(person.getAddress());
            }
        };
    }
}

 

ARC 결과

 

 

 

반응형

댓글