본문 바로가기

Study/개발일지

[백엔드온라인TIL] java 학습 15일차

0. 환경

  • m1 macbook
  • IntelliJ IDEA(m1) - 202102
  • java 11(AdoptOpenJDK-11.0.11)

1. build.gradle(JPA)

build.gradle 파일에 JPA, h2 데이터베이스 관련 라이브러리 추가합니다.

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
//	spring-boot-starter-data-jpa 는 내부에 jdbc 관련 라이브러리를 포함한다. 따라서 jdbc는 제거해도 된다.    
//	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	runtimeOnly 'com.h2database:h2'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

2. JPA

  • Java Persistence API
  • JPA는 기존의 반복 코드는 물론이고, 기본적인 SQL도 JPA가 직접 만들어서 실행해줍니다.
  • JPA를 사용하면, SQL과 데이터 중심의 설계에서 객체 중심의 설계로 패러다임을 전환을 할 수 있습니다.
  • JPA를 사용하면 개발 생산성을 크게 높일 수 있습니다.
  • JPA를 사용하려면 @Entity 매핑을 사용할 수 있어야 합니다.
    • JPA + Hibernate
    • JPA는 인터페이스만 제공합니다. = 자바 표준 인터페이스
    • Hibernate는 구현체이며 여러 가지 다른 구현체 라이브러리도 있으나 보통 JPA + Hibernate 조합으로 사용합니다.
  • JPA와 Hibernate는 ORM 기술입니다.
    • 객체와 관계형 데이터베이스의 데이터를 자동으로 매핑(연결)해줍니다. 
    • Object, Relational(RDB), Mapping(@Entity)
    • 객체 지향적인 코드로 인해 더 직관적이고 비즈니스 로직에 더 집중할 수 있습니다.
    • 재사용 및 유지보수의 편리성이 증가합니다.
    • DBMS에 대한 종속성이 줄어듭니다.

3. application.properties

spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

# show-sql : JPA가 생성하는 SQL을 출력한다.
# ddl-auto : JPA는 테이블을 자동으로 생성하는 기능을 제공하는데 none 를 사용하면 해당 기능을 끕니다.
	# create 를 사용하면 엔티티 정보를 바탕으로 테이블도 직접 생성해준다.
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
  • resources/application.properties
  • 스프링 부트에 JPA 설정 추가합니다.

 

 

@ResponseBody 문자 변환

  • @ResponseBody를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않습니다.
  • 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아닙니다.)
package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    ...

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }

}
728x90