현재 코드프레소에서 진행하고 있는 JAVA 웹개발 커리큘럼에 참여중에 있습니다.
그 중 Spring boot 초급과정에 대한 학습내용을 적어보고자 합니다.
- DB와 직접적으로 관련된 Data Access Layer 에 대해서 공부해보자
- Service 와 DB 사이에 위치한 Layer이다. DB가 변경되어도 Data Access Layer 코드가 변경될 순 있지만 나머지 Presentation 및 Application Layers 의 코드는 변경되면 안된다!!
Data Access Layer 에서 DB 에 접근 하는 기술 (내려갈수록 최신기술)
- JDBC (엄청 low함)
- JDBC Template (조금 low함)
- SQL Mapper (SQL 써두됨!)
- ORM (젤 high)
Mybatis 설정을 위한 준비단계
Maven 설정
- JAVA 프로젝트에서 사용되는 빌드 자동화 도구
- 프로젝트 구성 및 빌드를 도와줌
- 라이브러리 의존성 관리를 도와줌
- 원래는 외부 라이브러리를 개발자가 일일이 다운받고 명시했어야 했는데 Maven 을 통해 외부 라이브러리 다운 및 사용을 쉽게 도와준다
- pom.xml 에 외부 라이브러리 아래와 같은 형식으로 명시하면 됨 (dependency 하나 하나가 외부 라이브러리)
- 명시하는 것도 spring initializer 를 통해 편하게 가능
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
H2 Database
- RAM 으로도 활용 가능한 경량 RDBMS
- 별도의 설치 없이 Maven 의존성 만으로 사용가능해서 테스트에서 많이 쓰임
- 사용하려면 application.properties 에서 설정을 조금 해줘야함
- H2 DB 설정 (application.properties)
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:blog #mem:RAM 사용하겠다는 뜻 / blog: db이름
spring.datasource.username=sa #DB 접속 username
spring.datasource.password= #DB 접속 pswrd
- H2 DB 웹 설정 (application.properties)
spring.h2.console.enabled=true #웹 사용 설정
spring.h2.console.path=/h2-console #웹 URI path
- DB Table 초기화 (schema.sql)
- Spring 프로젝트의 resources 디렉토리 하위에 schema.sql 파일 생성 후 SQL 작성
drop table if exists comment CASCADE;
create table user_comment(
id bigint generated by default as identity,
post_id bigint not null,
user_name varchar(30) not null,
content varchar(300) not null,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP not null,
primary key (id)
);
- 데이터 초기화 (data.sql)
- data.sql 파일 생성 후 SQL 작성
INSERT INTO user (id, name, age) VALUES (1, "abc", 21)
INSERT INTO user (id, name, age) VALUES (2, "ccc", 30)
- mybatis 설정 파일 위치 추가 (application.properties)
# classpath 는 여러 root 경로들의 모음인데, resources도 그 중 하나
mybatis.config-location=classpath:mybatis/mybatis-config.xml
- MyBatis 설정파일 (mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
# 여러 개의 mapper를 여기에 추가한다
# 보통 table 당 1개의 ~Mapper.xml 파일을 갖게됨 (table에서 쓰이는 sql queries를 담는)
<mappers>
<mapper resource="mybatis/mapper/UserCommentMapper.xml"/>
<mapper resource="mybatis/mapper/PostMapper.xml"/>
</mappers>
</configuration>
정리하자면
- 스프링부트가 application.properties 를 읽어서 mybatis-config.xml (mybatis 설정 파일)이 어딨는지 찾음
- mybatis-config.xml 은 각 mapper들의 위치를 명시해줌
- 각 mapper들은 실제 쓰여지는 sql 쿼리가 담겨있음
application.properties → mybatis-config.xml → XXX.xml
MyBatis Mapper의 동작
- Application layer → Mapper(Repository, 인터페이스) 쪽을 호출함
- Mapper 인터페이스 → Mapper xml로 parameter(string, int, object ...) 를 보냄 <---JAVA와 SQL 사이의 데이터 교환을 MyBatis가 관리
- Mapper xml 에서 parameter를 가지고 SQL 을 완성하고 DB로 쿼리를 날림
중간중간 궁금한거
RequestCommentDto 는 html 에 있는 comment (JSON)를 가져올 때 쓰인다 (front -> back)
- 따라서, RequestCommentDto 에는 setter만 존재함 (JSON에서 가져와서 멤버변수를 초기화하고) 그걸 기반으로 comment vo를 만듦
ResponseCommentDto 는 db에 있는 comment(자바객체)를 가져올 떄 쓰인다 (back -> front)
- comment vo 를 db에서 가져와서 ResponseCommentDto 에 넣어서 front html 로 보내줌
- 근데 vo로 안보내고 Dto 로 꼭 보내야하는 이유가 뭘까???
질문
1. PostController 파일에서 "/post" 로 POST API 콜을 받았을때 (즉 createPost 함수를 불렀을때) PostRequestDto 자료형 postDto 에는 id에 쓰레기값이 들어가 있는건가요??? Post post = postDto.getPost(); 인데... postDto 안에는 id 초기화가 안되어있을텐데 여기에는 쓰레기값이 들어있나요??
- print 찍어보니 null 값이 들어가있네요. (자바는 C랑은 다르게 쓰레기값이 아니라 null이 들어가 있네요!)
- 그렇다면, PostRequestDto 에서 id는 필요가 없는거 아닌가요??
2.
$(document).on("click",".comment-edit-button",function(){
var content = $(".edit.comment-edit").val();
var id = $(".comment-id").val();
에서 class 이름을 기준으로 " .comment-id"를 찾을때 같은 class 이름("comment-id")을 가지는 다른 변수들도 있는데 무엇을 기준으로 찾는지 궁금하다.
-parent().parnet().children(".comment-id") 이런식으로 찾아야함
3. dto 와 vo 를 언제 나눠서 써야하는가...
- db 데이터를 담을 객체 (dto)
- controller -> service -> mapper 사이에서 데이터를 담을 객체 (vo)
- REST API 데이터를 담을 객체 ...
- 등등 경우에 따라 담고 싶은 데이터의 변수나 데이터.. 유출되면 안되는 (패스워드) 등등을 구분짓기 위해 dto, vo를 따로 객체로 만듦
'JAVA 웹개발 - 코드프레소' 카테고리의 다른 글
웹 "쿠키"와 "세션" (0) | 2022.03.05 |
---|---|
클라우드 컴퓨팅 첫 걸음 (0) | 2022.02.23 |
SQL 프로그래밍 입문 (0) | 2022.02.03 |
Spring Boot 웹 개발 입문 (0) | 2022.02.03 |
Clean Code란 무엇인가? (0) | 2022.01.25 |