JPA의 기본 개념에 대해 설명하고 MyBatis로 작성된 애플리케이션을 JPA로 리팩토링하는 과정을 단계별로 살펴봅니다.
목차
1. MyBatis
2. Why JPA?
3. MyBatis to JPA
- JPA 설정
- Entity
- 연관관계 설정
- Repository
- 애플리케이션에서의 사용
대상
- MyBatis를 실무에 사용하고 있으면서 JPA 도입을 고려하고 있는 백엔드 개발자
- JPA를 적용하면서 어려움을 겪었거나 JPA를 실제 적용하는 과정이 궁금한 개발자
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
Spring JPA를 이용한 연관 관계 매핑이나 Spring Data JPA Repository의 여러 기능들 중에서
막연하게만 알고 있었거나 널리 소개되지 못한 내용에 대해 함께 살펴봅니다.
목차
1. Spring JPA의 사실과 오해
2. 연관 관계 맵핑에 대한 모든 것
3. Spring Data JPA Repository의 숨겨진(?) 기능
대상
- Spring JPA에 대한 기본 지식이나 사용 경험은 있지만, 실무 적용에 여러 가지 어려움을 겪고 있는 개발자
- 막연히만 알고 사용했던 연관 관계 매핑이나 Spring Data JPA Repository에 대해 보다 깊이 있는 내용을 알고 싶은 개발자
■관련 동영상: https://youtu.be/kBXVCuZnV7Y
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
Spring JPA를 이용한 연관 관계 매핑이나 Spring Data JPA Repository의 여러 기능들 중에서
막연하게만 알고 있었거나 널리 소개되지 못한 내용에 대해 함께 살펴봅니다.
목차
1. Spring JPA의 사실과 오해
2. 연관 관계 맵핑에 대한 모든 것
3. Spring Data JPA Repository의 숨겨진(?) 기능
대상
- Spring JPA에 대한 기본 지식이나 사용 경험은 있지만, 실무 적용에 여러 가지 어려움을 겪고 있는 개발자
- 막연히만 알고 사용했던 연관 관계 매핑이나 Spring Data JPA Repository에 대해 보다 깊이 있는 내용을 알고 싶은 개발자
■관련 동영상: https://youtu.be/kBXVCuZnV7Y
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
I did this presentation for one of my java user groups at work.
Basically, this is a mashed up version of various presentations, slides and images that I gathered over the internet.
I've quoted the sources in the end. Feel free to reuse it as you like.
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
Chetan Mehrotra, Senior Computer Scientist, and Alex Parvulescu, Senior Developer, Adobe presented on Jan 20, 2016. They describe the features of Oak Lucene indexes and how they can be used to get your queries perform better. In the second part we will talk about how asynchronous indexing works in general and how it can be monitored.To view the on-demand session go to: http://bit.ly/AEMGems1202016 or for the MP4 version http://bit.ly/AEMGemsMP41202016
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
Introduction to the Thymeleaf java XML/XHTML/HTML5 template engine by José Miguel Samper and Daniel Fernández at Spring I/O 2012 Madrid, Feb 17th 2012.
NHN Forward 2018 컨퍼런스에서 발표한 자료입니다.
http://forward.nhnent.com/
MyBatis로 작성된 예제 프로그램을 JPA로 마이그레이션하는 방법에 대해 설명합니다.
cf.) https://github.com/nhnent/hands-on-labs.java.mybatis-to-jpa
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
I did this presentation for one of my java user groups at work.
Basically, this is a mashed up version of various presentations, slides and images that I gathered over the internet.
I've quoted the sources in the end. Feel free to reuse it as you like.
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
Chetan Mehrotra, Senior Computer Scientist, and Alex Parvulescu, Senior Developer, Adobe presented on Jan 20, 2016. They describe the features of Oak Lucene indexes and how they can be used to get your queries perform better. In the second part we will talk about how asynchronous indexing works in general and how it can be monitored.To view the on-demand session go to: http://bit.ly/AEMGems1202016 or for the MP4 version http://bit.ly/AEMGemsMP41202016
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
Introduction to the Thymeleaf java XML/XHTML/HTML5 template engine by José Miguel Samper and Daniel Fernández at Spring I/O 2012 Madrid, Feb 17th 2012.
NHN Forward 2018 컨퍼런스에서 발표한 자료입니다.
http://forward.nhnent.com/
MyBatis로 작성된 예제 프로그램을 JPA로 마이그레이션하는 방법에 대해 설명합니다.
cf.) https://github.com/nhnent/hands-on-labs.java.mybatis-to-jpa
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
패션 텍스트 데이터에서 패션 시소러스를 구축한 과정과 패션 상품 특징 분석 시스템에 대해 소개합니다.
패션 상품 특징을 어떻게 활용할 수 있는지에 대해 공유하고자 합니다.
목차
1. 개발 배경
2. 패션 시소러스 기반 상품 특징 분석 시스템 (A-Tagger)
3. A-Tagger 활용
대상
- 언어 처리 입문자
- 이미지 검색에 관심 있는 분
- 패션 업계 종사자
■관련 동영상: https://youtu.be/oGPqbvEkfxs
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
머릿속으로 그리던 나만의 앱, 생각만 잔뜩 하고 어디서부터 시작할지 고민 중이세요?
Android에 대한 가벼운 이해를 곁들여서 간단한 앱을 만들어가는 과정을 통해 (앱 개발이 생소한) 개발자들이 느끼는 Android 앱 개발의 진입장벽을 조금 낮춰보는 시간을 준비했습니다.
목차
1. 기획
2. 화면 개발
3. 서버 연동
4. 데이터 UI 바인딩
5. Play Store 출시
대상
Android 앱을 한번 만들어 보고 싶은 개발자라면 누구나
■관련 동영상: https://youtu.be/VhBKxRKPaSo
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
딥러닝을 처음 시작하시는 분, 특히 개발자에게 맞춰 필요한 내용을 준비하였습니다.
딥러닝의 수학적인 이해보다는 딥러닝을 활용하는 방법을 공유하고자 합니다.
목차
1. 딥러닝 권장 개발 환경
2. 코드 작성을 위한 약간의 이론
3. 가장 빠르게 그럴싸한 모델 만들기
대상
딥러닝에 관심이 있거나 딥러닝을 시작하려는 모든 개발자
※발표 영상은 제공하지 않습니다.
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
'베이스캠프(Basecamp)'는 NHN 신입 사원을 위한 개발 교육 과정입니다. 9주간의 교육 과정에서 무엇을 배웠고, 어떤 점이 좋고 힘들었는지 이야기하려 합니다.
목차
1. 5단 구성(발단-전개-위기-절정-결말)으로 베이스캠프 교육 과정 살펴보기
2. 그 과정에서 배웠던 점, 좋았던 점, 힘들었던 점
대상
NHN 신입사원 교육에 관심이 있는 주니어 개발자, 대학생
신입 개발자 교육을 정착시키고 싶은 시니어 개발자
※발표 영상은 제공하지 않습니다.
[2019] GIF 스티커 만들기: 스파인 2D를 이용한 움직이는 스티커 만들기NHN FORWARD
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
간단한 캐릭터를 그리고 완성된 캐릭터를 이용하여 포토샵에서 애니메이션이 가능하도록 분절에 대해 알려드리겠습니다. 분절이 완료되면 스파인에서 읽을 수 있게 내보내고 스파인에서 애니메이션 작업을 하겠습니다.
시간이 된다면 2가지 정도의 GIF 애니메이션을 제작할 예정입니다.
목차
1. 스프라이트 애니메이션과 키 애니메이션
2. 캐릭터 파트별로 분리하기
3. 캐릭터에 뼈대 심기
4. 애니메이션 만들기
5. GIF 출력
대상
- 이모티콘에 관심있는 누구나
- 애니메이션에 관심있는 누구나
■관련 동영상: https://youtu.be/7KqDL-D8dys
[2019] 전기 먹는 하마의 다이어트 성공기 클라우드 데이터 센터의 에너지 절감 노력과 사례NHN FORWARD
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
데이터 센터는 IT 장비의 안정적인 운영을 효율적이고 경제적으로 수행하는 것이 비교 우위에 있을 수 있습니다. 그중에서 이 시간에 다루고자 하는 것은 에너지의 효율성입니다.
데이터 센터에서 사용되는 전기 에너지는 어디에서 얼마나 사용되며 효율적으로 절감할 수 있었던 사례를 소개하고 NHN의 노력과 그 결과를 이야기하려 합니다.
목차
1. 클라우드 데이터센터는 ?
2. 에너지의 사용과 절감 ?
3. 모든 것을 측정 분석(DcIM) – 1st Tech
4. 효율적인 Cooling & Control(Cooling System) – 2nd Tech
5. Hot & Cold 분리(Containment) – 3rd Tech
대상
데이터 센터의 이야기에 관심 있는 분 누구나
■관련 동영상: https://youtu.be/-WHQUKAzdMs
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
Oracle을 MySQL로 전환하는 과정에서 경험했던 내용을 공유합니다.
이 세션을 들으시면 사전에 구체적인 계획을 세우고 체크리스트를 작성할 수 있습니다.
목차
1. 무엇을 어떻게 했나?
2. 어떤 이슈들이 있었나?
3. 도움이 될 만한 내용들
대상
- C++ 개발자
- Oracle과 MySQL의 차이점이 궁금한 분
- DB 전환 계획이 있는 분
■관련 동영상: https://youtu.be/9mTMlDN3rso
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
Oracle Database를 타 DBMS로 전환하기 위해 검토해야 하는 내용을 설명합니다
전환하려는 총괄 책임자는 어떠한 리스크가 발생하는지 검토해 볼 수 있습니다
DBA는 전환 작업을 하면서 전체 계획을 수립하는 데 도움을 받을 수 있습니다.
개발자는 전환 작업이 진행되면 어떠한 사항을 준비해야 하는지 전체적인 시야를 확보하게 됩니다.
목차
1. Open Source DBMS로의 전환
2. DBMS 전환 단계
3. Migration 예제 (to MySQL)
4. 전환 시스템 구성 및 용량 산정 방안
대상
- Open Source DBMS로 전환하고자 하는 DBA
- Open Source DBMS로 전환하고자 하는 개발자
- Oracle Database를 다른 DBMS로 전환하고자 하는 분
■관련 동영상: https://youtu.be/DXu3nbWa4AA
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
브랜드 디자인 프로세스와 디자인에 필요한 Basic System을 다양한 브랜드 사례로 설명합니다.
목차
1. 디자인 프로세스
2. 베이직 시스템
3. 적용 사례
대상
브랜드 디자인에 대한 기본적 이해가 필요하신 분
※영상자료는 공개하지 않습니다.
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
서버 사이드에서도 Spring 5를 통해 공식적으로 지원이 시작된 후,
Spring을 이용한 많은 서비스가 Java를 대신하여 Kotlin을 적용하고 있습니다.
본 세션에서는 PAYCO 매거진 프로젝트에 Kotlin을 적용했던 경험과 시행착오를 나누어 보려 합니다.
목차
1. Introduction
2. Motivation
3. Kotlin
4. Migration
5. Refactoring
6. Report
7. Conclusion
대상
Kotlin이라는 언어를 들어보신 분이라면 누구나
■관련 동영상: https://youtu.be/wiJqu7xoH58
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
벅스 Android 5.0에 Kotlin, Jetpack을 적용하면서 얻은 노하우와 시행착오를 공유합니다.
목차
1. 소개
2. Java to Kotlin
3. AAC (Android Architecture Components)
4. 미디어 앱 아키텍처(Media app architecture)
대상
- Kotlin과 Jetpack을 서비스에 적용하려는 Android 개발자
- 관련 Android 기술에 관심 있는 누구나
■관련 동영상: https://youtu.be/PqsjZn30XGE
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기NHN FORWARD
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
복잡하고 어려운 동시성(concurrency) 프로그래밍을 Fiber를 이용하여 성능은 유지하면서 간단하게 작성하는 방법을 알아봅니다.
Java에서 유저 모드 경량 스레드인 Fiber를 배우고 언제 어떻게 사용하면 좋을지 알게 됩니다.
목차
1. 동시성(concurrency) 프로그래밍이 어려운 이유
2. Fiber란 무엇인가?
3. Coroutine은 무엇인가?
4. Java Fiber Quasar
5. Fiber를 이용해 동시성 프로그래밍을 하는 방법
6. Fiber의 성능
7. 적용 사례 소개 (Tardis)
8. Java Fiber의 미래, Project Loom
9. Q&A
대상
- Java로 실시간 게임 서버를 만들고 싶은 분
- Java에서 동시성(concurrency) 프로그래밍을 쉽게 해보고 싶은 분
■관련 동영상: https://youtu.be/7H_ROv5rNIg
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
PAYCO 쇼핑의 아키텍처를 MSA로 변경하면서 겪은 삽질을 공유합니다.
레거시 서비스에서 서비스를 분리해내는 방법과 순서, 이후 고려해야 할 사항을 공유하고자 합니다.
목차
1. PAYCO 쇼핑?
2. 프로젝트 진행 과정
3. 아키텍처 공유
대상
- MSA, Spring cloud, Docker, Ansible 등을 실무에 적용하는 방법에 관심이 있는 분
- Spring Cloud를 써서 MSA로 개발하고 싶은데 어디서부터 손대야 할지 모르는 분
■관련 동영상: https://youtu.be/l195D5WT_tE
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
데이터에서 가치를 찾고 수익화하기까지 지난 1년간 겪었던 과정 및 국내 기업들이 찾는 데이터는 무엇이었는지 공유드리고자 합니다.
목차
1. 데이터로 인사이트를 찾는 여정
2. 인사이트에서 수익을 만들기까지
3. 데이터 제공 및 활용 사례
대상
- 데이터를 다루는 개발자
- 데이터 분석가
- 데이터로 사업을 고민하는 분
- 데이터 활용에 관심 있는 누구나
■관련 동영상: https://youtu.be/A9QiWjp1mb4
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
서버를 개발하면서 대규모 테스트를 어떤 식으로 진행할 것인지 고민하고 설계했던 내용과 그 과정에서 겪었던 시행착오를 공유하고자 합니다.
목차
1. 부하 테스트, 이것만 모니터링하면 끝?
2. Web, TCP Game Server
3. TCP Stress Test
4. 이렇게 모니터링해 보자
5. 시행착오
6. Q&A
대상
서버-클라이언트 테스트에 관심 있는 분 누구나
■관련 동영상: https://youtu.be/WhkZP4ZATmA
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
동접 200만 명이 접속할 수백 대의 게임 서버가 최소한의 MySQL 서버만으로 서비스할 수 있는 구조를 설명합니다.
고성능/고효율의 MySQL 스케일링 기법을 공유합니다. 대규모 게임 서비스에서 이미 검증된 것은 안 비밀~
목차
1. 기본적인 아기텍처
2. ProxySQL을 이용한 더 나은 아키텍처
3. 최종 아키텍처
대상
- 대규모 게임 서비스에 MySQL을 사용한 경험에 관심 있는 분
- ProxySQL에 관심이 있는 서버 개발자 혹은 DBA
- 게임 서버 개발 과정에서 DB 쪽을 유연하게 구성하고 싶은 분
■관련 동영상: https://youtu.be/8Eb_n7JA1yA
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
언리얼 엔진 프로그래밍을 시작하면, 편리하지만 한편으로는 골치아픈 UObject 시스템을 만나게 됩니다.
이 발표에서는 C++ 프로그래머를 대상으로 UObject 시스템과 그 핵심 기능인 리플렉션, 가비지 컬렉션을 소개하고 그 동작 원리를 함께 들여다봅니다.
목차
1. 일반적인 리플렉션의 개념
2. 언리얼엔진의 리플렉션
3. 일반적인 가비지컬렉션의 개념
4. 언리얼엔진의 가비지 컬렉션
대상
- C++ 개발자
- 언리얼 C++ 프로그래밍에 관심 있는 분
■관련 동영상: https://youtu.be/VpEe9DbcZIs
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
NHN의 게임은 어떻게 글로벌 서비스를 준비하는지, 시행착오와 이슈, 사례를 중심으로 공유합니다.
TOAST와 Gamebase 등 인프라와 플랫폼 중심의 해결 방식을 제안합니다.
목차
1. 왜 글로벌 서비스인가?
2. 처음 직면하게 될 문제들
3. 해외 이용자들의 다양한 요구
4. 사례 - 리소스 배포와 멀티 스레드 다운로드
5. 사례 - 글로벌 인프라 구성
6. 사례 - 보안 침해
7. 인프라 스케일링
대상
- 내 게임을 해외에 출시하고 싶은데, 어떤 기술적인 준비가 필요할지 궁금한 분
- NHN은 어떻게 글로벌에 게임 서비스를 하는지 궁금한 분
■관련 동영상: https://youtu.be/3O8RQboMMh8
[2019] 배틀로얄 전장(map) 제작으로 알아보는 슈팅 게임 레벨 디자인NHN FORWARD
※다운로드하시면 더 선명한 자료를 보실 수 있습니다.
배틀로얄 게임 전장(맵) 레벨 디자인의 경험과 노하우를 공유하려 합니다.
100인 이상의 PVP 사용자가 대전하는 오픈 필드 전장을 디자인할 때 레벨 기획자가 가져야 할 관점과 고려 사항을 다룹니다. 인도어 FPS와 오픈 필드 배틀로얄 게임의 레벨 관점 차이와 오픈 필드 전장을 효과적으로 제작하기 위한 작법을 사례와 함께 설명합니다.
목차
1. 범위 - 강연에서 다룰 레벨 디자인의 영역은?
2. 관점 - 일반 슈팅 맵과 배틀로얄 맵의 레벨 시각
3. 작법 - 어떤 방식으로 배틀로얄 맵을 만들 것인가?
4. 이슈 - 문제와 고민거리는 무엇인가?
대상
- FPS/TPS 레벨 디자인에 관심 있는 분
- 배틀로얄 게임 디자인에 관심 있는 분
■관련 동영상: https://youtu.be/ZWJKvCi3Njc
19. 생산성
JPA를 사용하면 지루하고 반복적인 CRUD용 SQL을 개발자가 직접 작성하지 않아도 된다
Spring Data JPA를 사용하면 interface 선언만으로도 쿼리 구현이 가능하기 때문에
관리 도구 등에서 가볍게 사용할 수 있는 CRUD 쿼리를 손쉽게 대처할 수 있다
JPA를 사용해야 하는 이유
구분 Order Item OrderItem
insert insert into Orders ( … ) insert into Items ( … ) insert into OrderItems ( …)
update update Orders set … update Items set … update OrderItems set …
delete delete from Orders … delete from Items … delete from OrderItems …
… … … …
20. JPA를 사용해야 하는 이유
public class Item {
private Long itemId;
private String itemName;
private Long price;
private String category;
}
유지보수
칼럼 추가/삭제 시 직접 관련된 CRUD 쿼리를 모두 수정하는 대신 JPA가 관리하는 모델(Entity)을 수정하면 된다
구분 Item
insert insert into Items ( item_id, item_name, price, category )
update update Items set item_name = ‘’, price = 0, category = ‘’
select select item_id, item_name, price, category from Items …
… …
21. 데이터 접근 추상화와 벤더 독립성
데이터베이스 벤더마다 미묘하게 다른 데이터 타입이나 SQL을 JPA를 이용하면 손쉽게 해결할 수 있다
JPA를 사용해야 하는 이유
Oracle MySql
22. SQL 중심적인 개발에서 객체 중심으로 개발
패러다임 불일치 해결
JPA는 객체와 관계형 데이터베이스 사이의 패러다임의 불일치로 발생하는 문제를 해결
(상속, 연관 관계, 객체 그래프 탐색 등)
JPA를 사용해야 하는 이유
24. JPA
Java Persistence API
자바 진영의 ORM 기술 표준
ORM(Object-Relational Mapping)
데이터베이스 객체를 자바 객체로 매핑하여 객체 간의 관계를 바탕으로 SQL을 자동으로 생성
25. JPA
표준 명세
JSR 338 – Java Persistence 2.2
Hibernate
JPA 실제 구현체 : Hibernate, EclipseLink, DataNuclues
Hibernate가 사실상 표준(de facto)
JPA, Hibernate
26. Spring Data
다양한 데이터 저장소에 대한 접근을 추상화하기 위한 Spring 프로젝트
JPA, JDBC, Redis, MongoDB, Elasticsearch 등
Spring Data JPA
Repository 추상화를 통해 interface 선언만으로도 구현 가능
메서드 이름으로 쿼리 생성
Web Support(페이징, 정렬, 도메인 클래스 컨버터 등)
Spring Data JPA
30. 빈 설정 – EntityManagerFactory
LocalContainerEntityManagerFactoryBean 빈 등록
SqlSessionFactoryBean vs EntityManagerFactoryBean
JPA 설정
@Bean LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf
= new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.nhnent.forward.mybatistojpa.entity");
emf.setJpaVendorAdapter(jpaVendorAdapters());
emf.setJpaProperties(jpaProperties());
return emf;
}
31. @Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
빈 설정 – TransactionManager
Transaction Manager 빈 등록
DataSourceTransactionManager vs JpaTransactionManager
JPA 설정
32. public interface EntityManager {
public <T> T find(Class<T> entityClass, Object primaryKey);
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);
public void persist(Object entity);
public <T> T merge(T entity);
public void remove(Object entity);
// ...
}
EntityManager
엔티티(Entity)의 저장, 수정, 삭제, 조회 등 엔티티와 관련된 모든 일을 처리하는 관리자
EntityManager
33. EntityManagerFactory
EntityManager를 생성하는 팩토리
EntityManagerFactory는 애플리케이션 전체에서 하나만 생성해서 공유
EntityManagerFactory
EntityManagerFactory EntityManager(s) Entity(s)생성 관리
35. Entity
JPA를 이용해서 데이터베이스 테이블과 매핑할 클래스
어노테이션
@Entity: JPA가 관리할 객체임을 명시
@Table: 매핑할 데이터베이스 테이블 이름을 명시
@Id: 기본 키(PK) 매핑
@Column: 필드와 칼럼을 매핑
Entity
36. @Entity
@Table(name = "Items")
public class ItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id")
private Long itemId;
@Column(name = "item_name")
private String itemName;
private Long price;
}
예) Entity 설정
ItemEntity 클래스
Entity
JPA가 관리할 객체
매핑할 테이블 이름
기본 키 매핑
필드와 칼럼 매핑
37. 자동 생성
• TABLE 전략: 채번 테이블을 사용
• SEQUENCE 전략: 데이터베이스 시퀀스를 사용해서 기본 키를 할당 e.g.) Oracle
• IDENTITY 전략: 기본 키 생성을 데이터베이스에 위임 e.g.) MySQL
• AUTO 전략: 선택한 데이터베이스 방언(dialect)에 따라 기본 키 매핑 전략을 자동으로 선택
직접 할당
• 애플리케이션에서 직접 식별자 값을 할당
기본 키 매핑 전략
38. public @interface GeneratedValue {
GenerationType strategy() default AUTO;
String generator() default "";
}
public enum GenerationType {
TABLE,
SEQUENCE,
IDENTITY,
AUTO
}
@GeneratedValue
기본 키 매핑 전략
45. 연관 관계(association)
• 데이터베이스 테이블 간의 관계(relationship)를 엔티티 클래스의 속성(attribute)으로 모델링
• 데이터베이스 테이블은 외래 키(FK)로 JOIN을 이용해서 관계 테이블을 참조
객체는 참조를 사용해서 연관된 객체를 참조
연관 관계 설정
46. 외래 키(FK) 매핑
@JoinColumn
다중성(Multiplicity)
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
연관 관계 설정
47. 연관 관계 설정
public class OrderItemEntity {
// ...
@ManyToOne
@JoinColumn(name = "item_id")
private ItemEntity item;
}
예) 연관 관계 설정
OrderItemEntity – ItemEntity 연관 관계 설정
50. 연관 관계 설정
public class OrderEntity {
@OneToMany(
mappedBy = "order",
cascade = { CascadeType.ALL }
)
List<OrderItemEntity> orderItems = new ArrayList<>();
}
public class OrderItemEntity {
@JoinColumn(name = "order_id")
@ManyToOne(fetch = FetchType.LAZY)
private OrderEntity order;
}
예) 연관 관계 설정
OrderEntity – OrderItemEntity 연관 관계 설정
양방향
관계의 주인
영속성 전이
52. // EntityManager를 통해 entity를 저장, 수정, 삭제, 조회
ItemEntity entity1 = new ItemEntity();
entity1.setItemName("peach");
entity1.setPrice(135L);
entityManager.persist(entity1);
ItemEntity entity2 = entityManager.find(ItemEntity.class, entity1.getItemId());
entity2.setPrice(235L);
entityManager.merge(entity2);
// JPQL, Criteria API를 이용해서 복잡한 쿼리 수행
String jpql = "select item from ItemEntity item where item.itemName like '%peach%'";
List<ItemEntity> entites = entityManager.createQuery(jpql, ItemEntity.class)
.getResultList();
Spring Data Repository
data access layer 구현을 위해 반복해서 작성했던, 유사한 코드를 줄일 수 있는 추상화 제공
Repository
53. public interface ItemRepository extends JpaRepository<ItemEntity, Long> {
}
예) Repository 설정
ItemRepository interface
JpaRepository interface 상속
Repository
55. // insert / update
<S extends T> S save(S entity);
// select * from Items where item_id = {id}
T findOne(ID id);
// select count(*) from Items;
long count();
// delete from Items where item_id = {id}
void delete(ID id);
// ...
JpaRepository가 제공하는 메서드들이 실제 수행하는 쿼리
Repository
56. 메서드 이름으로 쿼리 생성
public interface ItemRepository … {
// select * from Items where item_name like '%{itemName}%'
ItemEntity findByItemNameLike(String itemName);
// select item_id from Items where item_name = '{itemName}'
// and price = {price} limit 1
boolean existsByItemNameAndPrice(String itemName, Long price);
// select count(*) from Items where item_name like '%{itemName}%'
int countByItemNameLike(String itemName);
// delete from Items where price between {price1} and {price2}
void deleteByPriceBetween(long price1, long price2);
}
Spring Data JPA에서 제공하는 기능으로 이름 규칙에 맞춰 interface에 선언하면 쿼리 생성
cf.) https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
57. JPA에서 제공하는 객체 지향 쿼리
JPQL: 엔티티 객체를 조회하는 객체 지향 쿼리
Criteria API: JPQL을 생성하는 빌더 클래스
third party library를 이용하는 방법
Querydsl
jOOQ
…
복잡한 쿼리 작성
59. public class ItemService {
@Autowired
private ItemRepository itemRepository;
@Transactional
public Item createItem(Item item) {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemName(item.getItemName());
itemEntity.setPrice(item.getPrice());
ItemEntity newItem = itemRepository.save(itemEntity);
return newItem.toItemDto();
}
}
ItemService – insert
애플리케이션에서의 사용
60. 애플리케이션에서의 사용
public class ItemService {
@Autowired
private ItemRepository itemRepository;
@Transactional
public Item createItem(Item item) {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemName(item.getItemName());
itemEntity.setPrice(item.getPrice());
ItemEntity newItem
= itemRepository.save(itemEntity);
return newItem.toItemDto();
}
}
ItemService – insert vs MyBatis
VS
61. public class ItemService {
@Transactional
public Item updateItem(Item item) {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemId(item.getItemId());
itemEntity.setItemName(item.getItemName());
itemEntity.setPrice(item.getPrice());
ItemEntity newItemEntity = itemRepository.save(itemEntity);
return newItemEntity.toItemDto();
}
}
ItemService – update
애플리케이션에서의 사용
62. 애플리케이션에서의 사용
public class ItemService {
@Transactional
public Item updateItem(Item item) {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemId(item.getItemId());
itemEntity.setItemName(item.getItemName());
itemEntity.setPrice(item.getPrice());
ItemEntity newItemEntity
= itemRepository.save(itemEntity);
return newItemEntity.toItemDto();
}
}
ItemService – update vs MyBatis
VS
63. public class ItemService {
@Transactional
public boolean deleteItem(Long itemId) {
itemRepository.delete(itemId);
return true;
}
}
ItemService – delete
애플리케이션에서의 사용
64. 애플리케이션에서의 사용
public class ItemService {
@Transactional
public boolean deleteItem(Long itemId) {
itemRepository.delete(itemId);
return true;
}
}
ItemService – delete vs MyBatis
VS
66. public interface Pageable {
int getPageNumber();
int getPageSize();
int getOffset();
Sort getSort();
Pageable next();
Pageable previousOrFirst();
Pageable first();
boolean hasPrevious();
}
Spring Data 프로젝트에서 제공하는 web support 기능 중 하나
Pageable: pagination 정보를 추상화한 인터페이스
Pageable
67. @RestController
@RequestMapping("/items")
public class ItemController {
@Autowired
ItemService itemService;
@GetMapping("")
public List<Item> getItems(Pageable pageable) {
return itemService.getItems(pageable);
}
}
ItemController – Pageable 적용
Spring Data에서 page, size 파라미터값을 Controller의 Pageable 인자로 변환해서 전달
애플리케이션에서의 사용
GET /items?page=0&size=30
68. public class ItemService {
public List<Item> getItems(Pageable pageable) {
Page<ItemEntity> itemPage = itemRepository.findAll(pageable);
return itemPage.getContent()
.stream()
.map(ItemEntity::toItemDto)
.collect(Collectors.toList());
}
}
ItemService – pagination 구현
JpaRepository.findAll(Pageable pageable) 메서드로 Pageable 객체를 전달
애플리케이션에서의 사용
69. public class OrderService {
@Transactional
public Order createOrder(Order order) {
OrderEntity orderEntity = new OrderEntity();
orderEntity.setOrderDate(new Date());
order.getOrderItems()
.forEach(orderItem -> {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemId(orderItem.getItem().getItemId());
OrderItemEntity orderItemEntity = new OrderItemEntity();
orderItemEntity.setOrder(orderEntity);
orderItemEntity.getPk().setLineNumber(orderItem.getLineNumber());
orderItemEntity.setItem(itemEntity);
orderItemEntity.setQuantity(orderItem.getQuantity());
orderEntity.getOrderItems().add(orderItemEntity);
});
OrderEntity newEntity = orderRepository.save(orderEntity);
return newEntity.toOrderDto();
}
}
OrderService – insert
영속성 전이를 이용해서 OrderEntity를 저장할 때 OrderItemEntity도 함께 저장
애플리케이션에서의 사용
70. 애플리케이션에서의 사용
public class OrderService {
@Transactional
public Order createOrder(Order order) {
OrderEntity orderEntity = new OrderEntity();
orderEntity.setOrderDate(new Date());
order.getOrderItems()
.forEach(orderItem -> {
ItemEntity itemEntity = new ItemEntity();
itemEntity.setItemId(orderItem.getItem().getItemId());
OrderItemEntity orderItemEntity = new OrderItemEntity();
orderItemEntity.setOrder(orderEntity);
orderItemEntity.getPk().setLineNumber(orderItem.getLineNumber());
orderItemEntity.setItem(itemEntity);
orderItemEntity.setQuantity(orderItem.getQuantity());
orderEntity.getOrderItems().add(orderItemEntity);
});
OrderEntity newEntity = orderRepository.save(orderEntity);
return newEntity.toOrderDto();
}
}
OrderService – insert vs MyBatis
VS
71. JPA 설정
spring-data-jpa, hibernate-entitymanager 의존성 라이브러리 추가
EntityManagerFactoryBean, JpaTransactionManager 빈 등록
Entity 설정
@Entity, @Table, @Id, @Column, @Temporal, @GeneratedValue, @EmbeddedId, …
연관 관계 설정
@JoinColumn, @OneToMany, @ManyToOne, mappedBy, FetchType.LAZY, …
Repository interface 생성 - JpaRepository 상속
애플리케이션에서의 사용 – Entity, Repository, Pageable, …
MyBatis to JPA Summary
72. 상대적으로 높은 학습 곡선
But,
기술적인 진입 장벽을 낮춰줄 여러 솔루션들이 존재(e.g. Spring Data JPA, QueryDSL 등)
2015년 이후로 JPA 관련 다양한 국내 서적이 출간된 상태
JPQL에는 분명 한계가 있다
But,
Native SQL
다른 Data Access 기술과 혼용 및 분리(CQRS) 가능
그럼에도 불구하고 …
JPA의 단점
73. 그 동안 MyBatis로 마이 버팃으면
이제는 JPA를 한 번 써 봐야 할 때
MyBatis에서 JPA로!