ORM 을 이해하기 위해서는 먼저 영속성이라는 개념을 이해해야 한다.
1. Persistence - 영속성
영속성은 데이터를 생성했던 프로그램이 종료되더라도 데이터가 없어지지 않는 것을 말한다.
예를 들어서, 일기장 앱에서도 어플을 켰다가 꺼도 일기가 지워지지는 않는다.
이것이 바로 데이터의 영속성이라고 말을 할 수 있다.
데이터의 영속성은 즉, 결국 DB를 사용해야 한다는 뜻이다!
1.1. Persistence Framework
위에서 말했듯이 결국 DB인 영속성 있는 데이터를 사용하기 편하게 해주는 것이 바로 Persistence Framework이다. Persistence Framework 는 DB 와의 연동되는 시스템을 빠르게 개발하고, 안정적인 구동을 보장해 주는 프레임워크를 말한다.
1.1.2 Persistence Framework 종류
Persistence Framework의 종류에는 SQL Mapper와 ORM 이 있다.
(1) SQL Mapper
- SQL을 직접 작성한다.
- SQL 문과 객체(Object)의 필드를 매핑하여 데이터를 객체화한다.
- SQL Mapper 단점
- DB 종류 변경 시 쿼리 수정이 필요하다.
- 비슷한 쿼리를 반복적으로 작성해야 한다.
(2) ORM (Object Relation Mapping)
- Object와 DB 테이블을 매핑하여 데이터를 객체화와 한다.
- ORM을 이용하면 쿼리문 작성이 아닌 코드(메서드)로 데이터를 조작할 수 있다.
2. ORM의 장단점
(1) 장점
- ORM을 사용하면서 쿼리를 객체지향적으로 조작할 수 있다.
- 쿼리문을 작성하는 양이 현저히 줄어 개발 비용이 줄어든다.
- 객체지향적으로 데이터베이스에 접근할 수 있어 코드의 가독성을 높인다.
- 재사용 및 유지보수가 편리하다.
- ORM 을 통해 매핑된 객체는 모두 독립적으로 작성되어 있어 재사용이 용이하다.
- 객체들은 각 클래스로 나뉘어 있어 유지보수가 수월하다.
- 데이터베이스에 대한 종속성이 줄어든다.
- ORM 을 통해 자동 생성된 SQL 문은 객체를 기반으로 데이터베이스 테이블을 관리하기 때문에 데이터베이스에 종속적이지 않다.
(2) 단점
- ORM 만으로 온전한 서비스를 구현하는 데에는 한계가 있다.
- 복잡한 서비스의 경우 직접 쿼리를 구현하지 않고 코드로 구현하기 어렵다.
- 복잡한 쿼리를 정확한 설계 없이 ORM 만으로 구성하게 되면 속도 저하 등의 성능 문제가 발생할 수 있다.
3. JPA vs JDBC
JPA와 JDBC는 각 각 SQL Mapper와 ORM의 일종 중 하나이다.
3.1 JDBC (Java Database Connectivity)
JDBC는 SQL Mapper 중 하나이다.
예시로, Application을 현재 진행하고 있는 스프링부트 프로젝트라고 하고
Persistence Layer를 현재 사용하고 있는 DB라고 가정해 보자.
Application과 Persistence Layer 사이에서 JDBC 가 쿼리를 날림으로써 이 사이를 매핑한다고 생각하면 된다.
3.2 JPA (Java Persistence API)
JPA는 ORM 중 하나이다.
JPA의 메커니즘을 보면 내부적으로 JDBC를 사용한다.
개발자가 직접 JDBC 를 구현하면 SQL에 의존하게 되는 문제 등이 있어 개발의 효율성이 떨어지는데,
JPA는 이와 같은 문제점을 보완해서 개발자 대신 적절한 SQL을 생성하고 데이터베이스를 조작해서 객체를 자동 매핑하는 역할을 수행한다.