26
What is Persistence in Java 김병부 (Benjamin Kim) [email protected] http://myboor.tistory.com

What is persistence in java

Embed Size (px)

Citation preview

What is Persistence in Java

김 병 부 (Benjamin Kim)[email protected]

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, lowperformance

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.09Create and Insert 10 Employees

0.73 0.9 0.67

Update 10 Employees 0.58 0.55 0.7Update 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

@PersistenceContextprivate EntityManagerFactory emf; // ... EntityManager em = emf.createEntityManager();

Customer customer = new Customer(id, name, address); em.persist(customer);

Customer customer = em.find(Customer.class, id); // Readcustomer.setAddress(“new Address String”); // Updateem.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/