SlideShare a Scribd company logo
1 of 26
What is
Persistence
in Java
김 병 부 (Benjamin Kim)
byungboor@naver.com
http://myboor.tistory.com
About what?
• History
• JPA Features
• Persistence
• ORM
• JPA CRUD
• JPA Entity LifeCycle
• Why Hibernate?
• Spring Data JPA
Market Situation
Market Situation
Hibernate VS MyBatis VS JDBC
Criteria JDBC MyBatis Hibernate
Learning Curve Simple to learn Simple to learn Many aspects to learn
Work in data centric env Good, mapping efforts
exits
Naturally fits Mapping issues, low
performance
Work in obj centric env Major mapping efforts Good, limited feature
amount
Naturally fits
Object Mapping Manual, hard to support Maps methods to
statements
Transparent persistence
Query Language Native SQL Native SQL HQL, Native SQL,
Criteria API
Caching Poor,
manual or 3rd party
Good customization 3 level, advanced
customization
Hibernate VS MyBatis VS JDBC Performance test
Test JDBC MyBatis Hibernate
Read 5k Employees
0.51 0.77 8.09
Create and Insert 10
Employees
0.73 0.9 0.67
Update 10 Employees
0.58 0.55 0.7
Update 10 Employee
Addresses
0.28 0.2 0.41
Cascade delete of 10
Employees
2.25 0.71 0.79
History
EJB-Entity Bean
Hibernate
JPA v1.0 (2006. 5) JPA v2.0 (2009.12) JPA v2.1 (2013)
Spring Data
Spring-Data-JPA
History
JPA
OpenJPA EclipseLink Hibernate
JPA Features
• JPA 2.0
– Expanded object-relational mapping functionality
– Criteria query API
– Query Hints 표준
– DDL 생성 metadata 표준
– Validation
– Shared Object cache support
• JPA 2.1
– Converters - allowing custom code conversions between database and object types.
– Criteria Update/Delete - allows bulk updates and deletes through the Criteria API.
– Stored Procedures
– Schema Generation
– Entity Graphs - allow partial or specified fetching or merging of objects.
– JPQL/Criteria 강화 - arithmetic sub-queries, generic database functions, join ON clause, TREAT option.
Persistence
• Persistence
– 사전적 의미 : 고집, 지속, 영속성 or 영속화
– 보편적 의미의 Persistence는 Application이나 Object가 수명을 다했을 때도, Object의 데이터가 저장되
는 것을 의미한다.
– 저장소 : DBMS, File 등등
• Persistence Object in JAVA
– 이미 익숙한 객체
– POJO 기반의 클래스 객체
– Java Bean Style – private 속성, getter/setter
– Persistence Object = Table의 1개 Row
ORM
• ORM (Object-Relational Mapping)
– 관계형 데이터와 객체 데이터를 서로 맵핑 시키는것.
– Persistence Object 를 처리 해주는 것.
– E.g. Hibernate F/W
• What is difference between Mybatis and Hibernate
– Database-centric VS Object-centric
– Mybatis is focusing on SQL Mapping Persistent F/W
– Hibernate is focusing on ORM framework
JPA CRUD
• EntityManager
– Application-managed EntityManager, Container-managed EntityManager
– DB에서 Entity 와 관련된 작업 API(CRUD)를 제공한다.
– Create
– Read, Update, Delete
@PersistenceContext
private EntityManagerFactory emf;
// ...
EntityManager em = emf.createEntityManager();
Customer customer = new Customer(id, name, address);
em.persist(customer);
Customer customer = em.find(Customer.class, id); // Read
customer.setAddress(“newAddressString”); // Update
em.remove(customer) // Delete
JPA Entity LifeCycle
• NEW
– Entity 인스턴스만 생성된 상태 – DB와 연결이 없다.
• Managed
– Persistence Context에 의해서 관리되는 상태
– Entity 내부 속성값이 바뀌면 DB에 반영 (Update됨)
• Detached
– Entity Instance 가 Persistence Context 에 의해서 관리되지 않는 상태
– EntityManager의 merge() 로 Managed 상태로 천이 가능
• Removed
– DB에서 Entity 가 삭제되는 상태
Why Hibernate?
• Advantage
– DDD
– 생산성
– 이식성
– 트렌드
• Disadvantage
– 성능에 대한 부담감
– 복잡한 Domain 구조에서의 부족한 설계 경험
– 너무나 익숙한 SQL
그럼에도 불구하고 Hibernate.
Why Hibernate?
• Hibernate supported Databases
– MySQL (innoDB, MyISAM)
– Oracle (any version)
– DB2
– PostgreSQL
– Informix
– H2
– DERBY
– SQL_SERVER
– SYBASE
Spring Data JPA
• http://projects.spring.io/spring-data/
• One of sub project of Spring-DATA
– MongoDB, NEO4J, REDIS, SOLAR, HADOOP, ElasticSearch, CouchBase, Cassandra,
DynamoDB, JDBC Extentions
• Anti - Boiler-plate structure
– 정해진 규칙에 따라 인터페이스 생성시 단순 노동을 줄일 수 있음
Spring Data JPA
• In case of Mybatis, to develop User domain
– UserMapper.xml
• CRUD Queries and Another Search Queries
– UserMapper.java interface
• CRUD Methods and Another Search Methods mapped with UserMapper.xml
– UserDao.java interface
• CRUD and Search Methods for DAO Layer
– UserDaoImpl.java class
• CRUD and Search implementation Methods
– UserValue domain class
• In case of Hibernate, to develop User domain
– Only required UserRepository similar to UserDao interface. That’s all
– User domain class with some annotation
Spring Data JPA
• Entity
Spring Data JPA
• Repository
– org.springframework.data.Repository Interface in Spring-Data-JPA
Spring Data JPA
• Repository Naming Rule
Operation Rule
Read T findOne(ID primaryKey)
List<T> findAll()
List<T> findByDeptName(String deptName)
List<T> findByDeptNameAndPhone(String deptName, phone)
List<T> findByPhoneIn(Collection<String> phones)
List<T> findByNameStartingWith(String name)
List<T> findByNameEndingWith(String name)
List<T> findByNameIgnoreCase(String name)
Long count()
Long countByDeptName(String deptName)
Create T save(T t)
Delete void delete(Long id);
void delete(T t);
void delete(List<T> entities);
void deleteAll();
Spring Data JPA
• 검색조건 Specification
– org.springframework.data.jpa.domain.Specification
• 정렬조건
– org.springframework.data.domain.Sort
• 페이징 처리
– org.springframework.data.domain.Pageable
Spring Data JPA
<<interface>>
Repository
<<interface>>
CrudRepository
<<interface>>
PagingAndSortingRepository
<<interface>>
JpaRepository
<<interface>>
JpaSpecificationExecutor
Development Stack
Reference Link
• http://en.wikipedia.org/wiki/Java_Persistence_API
• http://www.javajigi.net/pages/viewpage.action?pageId=5924
• http://www.youtube.com/watch?v=OOO4H3BAetU
• http://hibernate.org/orm/what-is-an-orm/
• http://www.slideshare.net/iwish1hadanose/hibernate-vs-my-batis-vs-jdbc-is-there-a-
silver-bullet
• http://zeroturnaround.com/rebellabs/
What is persistence in java
What is persistence in java

More Related Content

Similar to What is persistence in java

Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...Vladimir Bacvanski, PhD
 
No sql solutions - 공개용
No sql solutions - 공개용No sql solutions - 공개용
No sql solutions - 공개용Byeongweon Moon
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...OpenBlend society
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Javasunnygleason
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfPatiento Del Mar
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMPT.JUG
 
Microsoft Openness Mongo DB
Microsoft Openness Mongo DBMicrosoft Openness Mongo DB
Microsoft Openness Mongo DBHeriyadi Janwar
 
An Overview of ModeShape
An Overview of ModeShapeAn Overview of ModeShape
An Overview of ModeShapeRandall Hauch
 
Hadoop Summit - Hausenblas 20 March
Hadoop Summit - Hausenblas 20 MarchHadoop Summit - Hausenblas 20 March
Hadoop Summit - Hausenblas 20 MarchMapR Technologies
 
Understanding the Value and Architecture of Apache Drill
Understanding the Value and Architecture of Apache DrillUnderstanding the Value and Architecture of Apache Drill
Understanding the Value and Architecture of Apache DrillDataWorks Summit
 
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"Anna Shymchenko
 
Engineering practices in big data storage and processing
Engineering practices in big data storage and processingEngineering practices in big data storage and processing
Engineering practices in big data storage and processingSchubert Zhang
 

Similar to What is persistence in java (20)

Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...
 
No sql solutions - 공개용
No sql solutions - 공개용No sql solutions - 공개용
No sql solutions - 공개용
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
 
Apache Drill
Apache DrillApache Drill
Apache Drill
 
Hibernate
HibernateHibernate
Hibernate
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Java
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdf
 
Hibernate
HibernateHibernate
Hibernate
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
 
Microsoft Openness Mongo DB
Microsoft Openness Mongo DBMicrosoft Openness Mongo DB
Microsoft Openness Mongo DB
 
Drill njhug -19 feb2013
Drill njhug -19 feb2013Drill njhug -19 feb2013
Drill njhug -19 feb2013
 
An Overview of ModeShape
An Overview of ModeShapeAn Overview of ModeShape
An Overview of ModeShape
 
Hadoop Summit - Hausenblas 20 March
Hadoop Summit - Hausenblas 20 MarchHadoop Summit - Hausenblas 20 March
Hadoop Summit - Hausenblas 20 March
 
Understanding the Value and Architecture of Apache Drill
Understanding the Value and Architecture of Apache DrillUnderstanding the Value and Architecture of Apache Drill
Understanding the Value and Architecture of Apache Drill
 
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"
Евгений Варфоломеев "Hibernate vs my batis vs jdbc: is there a silver bullet?"
 
Engineering practices in big data storage and processing
Engineering practices in big data storage and processingEngineering practices in big data storage and processing
Engineering practices in big data storage and processing
 
Mongodb my
Mongodb myMongodb my
Mongodb my
 

Recently uploaded

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

What is persistence in java

  • 1. What is Persistence in Java 김 병 부 (Benjamin Kim) byungboor@naver.com http://myboor.tistory.com
  • 2. About what? • History • JPA Features • Persistence • ORM • JPA CRUD • JPA Entity LifeCycle • Why Hibernate? • Spring Data JPA
  • 5. Hibernate VS MyBatis VS JDBC Criteria JDBC MyBatis Hibernate Learning Curve Simple to learn Simple to learn Many aspects to learn Work in data centric env Good, mapping efforts exits Naturally fits Mapping issues, low performance Work in obj centric env Major mapping efforts Good, limited feature amount Naturally fits Object Mapping Manual, hard to support Maps methods to statements Transparent persistence Query Language Native SQL Native SQL HQL, Native SQL, Criteria API Caching Poor, manual or 3rd party Good customization 3 level, advanced customization
  • 6. Hibernate VS MyBatis VS JDBC Performance test Test JDBC MyBatis Hibernate Read 5k Employees 0.51 0.77 8.09 Create and Insert 10 Employees 0.73 0.9 0.67 Update 10 Employees 0.58 0.55 0.7 Update 10 Employee Addresses 0.28 0.2 0.41 Cascade delete of 10 Employees 2.25 0.71 0.79
  • 7. History EJB-Entity Bean Hibernate JPA v1.0 (2006. 5) JPA v2.0 (2009.12) JPA v2.1 (2013) Spring Data Spring-Data-JPA
  • 9. JPA Features • JPA 2.0 – Expanded object-relational mapping functionality – Criteria query API – Query Hints 표준 – DDL 생성 metadata 표준 – Validation – Shared Object cache support • JPA 2.1 – Converters - allowing custom code conversions between database and object types. – Criteria Update/Delete - allows bulk updates and deletes through the Criteria API. – Stored Procedures – Schema Generation – Entity Graphs - allow partial or specified fetching or merging of objects. – JPQL/Criteria 강화 - arithmetic sub-queries, generic database functions, join ON clause, TREAT option.
  • 10. Persistence • Persistence – 사전적 의미 : 고집, 지속, 영속성 or 영속화 – 보편적 의미의 Persistence는 Application이나 Object가 수명을 다했을 때도, Object의 데이터가 저장되 는 것을 의미한다. – 저장소 : DBMS, File 등등 • Persistence Object in JAVA – 이미 익숙한 객체 – POJO 기반의 클래스 객체 – Java Bean Style – private 속성, getter/setter – Persistence Object = Table의 1개 Row
  • 11. ORM • ORM (Object-Relational Mapping) – 관계형 데이터와 객체 데이터를 서로 맵핑 시키는것. – Persistence Object 를 처리 해주는 것. – E.g. Hibernate F/W • What is difference between Mybatis and Hibernate – Database-centric VS Object-centric – Mybatis is focusing on SQL Mapping Persistent F/W – Hibernate is focusing on ORM framework
  • 12. JPA CRUD • EntityManager – Application-managed EntityManager, Container-managed EntityManager – DB에서 Entity 와 관련된 작업 API(CRUD)를 제공한다. – Create – Read, Update, Delete @PersistenceContext private EntityManagerFactory emf; // ... EntityManager em = emf.createEntityManager(); Customer customer = new Customer(id, name, address); em.persist(customer); Customer customer = em.find(Customer.class, id); // Read customer.setAddress(“newAddressString”); // Update em.remove(customer) // Delete
  • 13. JPA Entity LifeCycle • NEW – Entity 인스턴스만 생성된 상태 – DB와 연결이 없다. • Managed – Persistence Context에 의해서 관리되는 상태 – Entity 내부 속성값이 바뀌면 DB에 반영 (Update됨) • Detached – Entity Instance 가 Persistence Context 에 의해서 관리되지 않는 상태 – EntityManager의 merge() 로 Managed 상태로 천이 가능 • Removed – DB에서 Entity 가 삭제되는 상태
  • 14. Why Hibernate? • Advantage – DDD – 생산성 – 이식성 – 트렌드 • Disadvantage – 성능에 대한 부담감 – 복잡한 Domain 구조에서의 부족한 설계 경험 – 너무나 익숙한 SQL 그럼에도 불구하고 Hibernate.
  • 15. Why Hibernate? • Hibernate supported Databases – MySQL (innoDB, MyISAM) – Oracle (any version) – DB2 – PostgreSQL – Informix – H2 – DERBY – SQL_SERVER – SYBASE
  • 16. Spring Data JPA • http://projects.spring.io/spring-data/ • One of sub project of Spring-DATA – MongoDB, NEO4J, REDIS, SOLAR, HADOOP, ElasticSearch, CouchBase, Cassandra, DynamoDB, JDBC Extentions • Anti - Boiler-plate structure – 정해진 규칙에 따라 인터페이스 생성시 단순 노동을 줄일 수 있음
  • 17. Spring Data JPA • In case of Mybatis, to develop User domain – UserMapper.xml • CRUD Queries and Another Search Queries – UserMapper.java interface • CRUD Methods and Another Search Methods mapped with UserMapper.xml – UserDao.java interface • CRUD and Search Methods for DAO Layer – UserDaoImpl.java class • CRUD and Search implementation Methods – UserValue domain class • In case of Hibernate, to develop User domain – Only required UserRepository similar to UserDao interface. That’s all – User domain class with some annotation
  • 19. Spring Data JPA • Repository – org.springframework.data.Repository Interface in Spring-Data-JPA
  • 20. Spring Data JPA • Repository Naming Rule Operation Rule Read T findOne(ID primaryKey) List<T> findAll() List<T> findByDeptName(String deptName) List<T> findByDeptNameAndPhone(String deptName, phone) List<T> findByPhoneIn(Collection<String> phones) List<T> findByNameStartingWith(String name) List<T> findByNameEndingWith(String name) List<T> findByNameIgnoreCase(String name) Long count() Long countByDeptName(String deptName) Create T save(T t) Delete void delete(Long id); void delete(T t); void delete(List<T> entities); void deleteAll();
  • 21. Spring Data JPA • 검색조건 Specification – org.springframework.data.jpa.domain.Specification • 정렬조건 – org.springframework.data.domain.Sort • 페이징 처리 – org.springframework.data.domain.Pageable
  • 24. Reference Link • http://en.wikipedia.org/wiki/Java_Persistence_API • http://www.javajigi.net/pages/viewpage.action?pageId=5924 • http://www.youtube.com/watch?v=OOO4H3BAetU • http://hibernate.org/orm/what-is-an-orm/ • http://www.slideshare.net/iwish1hadanose/hibernate-vs-my-batis-vs-jdbc-is-there-a- silver-bullet • http://zeroturnaround.com/rebellabs/