환경 설정 이어서..
메모리 DB 설정 및 연결 확인
application.yml
server:
port: 8081
spring:
application:
name: demo
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:testdb
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true
generate-ddl: true
defer-datasource-initialization: true
h2:
console:
enabled: true
settings:
web-allow-others: true
path: /h2-console
일반적인 스프링 패키지 구조
Client ---> 서블릿 컨테이너(= 톰캣 = WAS) ---HTTP Message 파싱 및 전달--> Controller -> Service -> Repository
Controller Component 작성
Controller에서 서버에 전송된 HTTP Message를 HTTP Method와 Param, Body 파싱하는 예시 사례 정리
https://charactermail.tistory.com/357
package com.example.demo.controller;
import com.example.demo.dto.test.TestDto;
import com.example.demo.entity.TestEntity;
import com.example.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1")
public class TestController {
TestService testService;
@Autowired
TestController(TestService testService){
this.testService = testService;
}
// http://127.0.0.1:8081/api/v1/
@GetMapping(value = "/")
public String getMapping(){
return "getMapping";
}
// http://127.0.0.1:8081/api/v1/test?name=yb&age=3
@GetMapping(value = "/test")
public String getMapping1(@RequestParam String name, @RequestParam int age){
return name + " " + age;
}
// http://127.0.0.1:8081/api/v1/test2?nickname=yb&age=3
@GetMapping(value = "/test2")
public String getMapping2(@RequestParam(name = "nickname") String name, @RequestParam int age){
return name + " " + age;
}
// http://127.0.0.1:8081/api/v1/test3/99
@GetMapping(value = "/test3/{id}")
public String getMapping3(@PathVariable(name = "id") int age){
return ""+age;
}
@PostMapping("/")
public String postMapping(){
return "postMapping";
}
// http://127.0.0.1:8081/api/v1/test
/*
{
"id":3,
"name":"yb",
"age":3
}
*/
@PostMapping("/test")
public String postMapping1(@RequestBody TestDto testDto){
System.out.println("testDto = " + testDto);
return testDto.toString();
}
@PutMapping("")
public String putMapping(){
return "put mapping";
}
@DeleteMapping
public String deleteMapping(){
return "delete Mapping";
}
//------------------------------------------------------------------------
// http://127.0.0.1:8081/api/v1/
@GetMapping(value = "/testentity")
public List<TestEntity> getAllTestEntity(){
return testService.getAllTestEntity();
}
// http://127.0.0.1:8081/api/v1/
/*
{
"name":"yb",
"age":3
}
*/
@PostMapping(value = "/testentity")
public void saveTestEntity(@RequestBody TestDto testDto){
testService.saveEntity(testDto);
}
}
Service Component 작성
package com.example.demo.service;
import com.example.demo.dto.test.TestDto;
import com.example.demo.entity.TestEntity;
import com.example.demo.repository.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TestService {
private final TestRepository testRepository;
@Autowired
public TestService(TestRepository testRepository){
this.testRepository = testRepository;
}
public void saveEntity(TestDto testDto){
TestEntity testEntity = TestEntity.createTestDtoFromEntity(testDto);
testRepository.save(testEntity);
}
public List<TestEntity> getAllTestEntity(){
return testRepository.findAllEntity();
}
}
Repository Component 작성
package com.example.demo.repository;
import com.example.demo.entity.TestEntity;
import org.aspectj.weaver.ast.Test;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TestRepository extends JpaRepository<TestEntity, Long> {
// QueryMethod
TestEntity findByAge(int age);
// JPQL 문법, 오른쪽 MySQL 쿼리와 동일 SELECT * FROM TestEntity;
@Query("select t from TestEntity t")
List<TestEntity> findAllEntity();
// // Spring Data JPA @Query 어노테이션 활용 - JPQL 문법 Version
// @Query("select t from TestEntity t where t.age >= :age")
// List<TestEntity> findEntityLargeThanAge(@Param("age") int age);
//
// // Spring Data JPA @Query 어노테이션 활용 - Native SQL 문법 Version
// @Query(value = "select * from TEST_ENTITY where age >= :age", nativeQuery = true)
// List<TestEntity> findEntityLargeThanAgeNativeQuery(@Param("age") int age);
}
Entity Component 작성
package com.example.demo.entity;
import com.example.demo.dto.test.TestDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@Builder
@Table(name = "TestEntity")
@NoArgsConstructor
@AllArgsConstructor
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private int age;
public static TestEntity createTestDtoFromEntity(TestDto testDto){
return TestEntity.builder()
.name(testDto.getName())
.age(testDto.getAge())
.build();
}
}
Dto Component 작성
package com.example.demo.dto.test;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class TestDto {
private String name;
private int age;
}
댓글