본문 바로가기
공식문서

[Spring Docs] Introduction to ORM with Spring

by sangyunpark99 2025. 4. 21.

이번글은 공식 문서에서 소개하는 Introduction to ORM with Spring에 대해 정리했습니다.

 

The Spring Framework supports integration with the Java Persistence API (JPA) and supports native Hibernate for resource management, data access object (DAO) implementations, and transaction strategies. For example, for Hibernate, there is first-class support with several convenient IoC features that address many typical Hibernate integration issues. You can configure all of the supported features for OR (object relational) mapping tools through Dependency Injection. They can participate in Spring’s resource and transaction management, and they comply with Spring’s generic transaction and DAO exception hierarchies. The recommended integration style is to code DAOs against plain Hibernate or JPA APIs.

 

Spring Framework는 Java Persistence API(JPA)와의 통합을 지원하고, Hibernate에 대해서도 별도로 강력한 통합 기능을 제공합니다. 구체적으로 말하면, 자원 관리, DAO 구현, 트랜잭션 처리 전략 같은 부분에서 Hibernate를 사용하는 데에 필요한 다양한 기능들을 IoC 기반으로 편리하게 구성할 수 있습니다.

 

이러한 ORM 도구들은 전부 스프링의 의존성 주입(Dependency Injection)을 통해 설정할 수 있고, 스프링의 자원 관리 및 트랜잭션 처리 흐름 안에서 함께 동작할 수 있습니다. 또한 예외 처리도 스프링이 제공하는 일관된 DAO/트랜잭션 예외 계층을 따르도록 되어 있습니다.

 

스프링에서 권장하는 방식은, DAO를 작성할 때 스프링 전용 API가 아니라, 순수한 Hibernate나 JPA API를 기반으로 구현하는 것입니다.

 

Spring adds significant enhancements to the ORM layer of your choice when you create data access applications. You can leverage as much of the integration support as you wish, and you should compare this integration effort with the cost and risk of building a similar infrastructure in-house. You can use much of the ORM support as you would a library, regardless of technology, because everything is designed as a set of reusable JavaBeans. ORM in a Spring IoC container facilitates configuration and deployment. Thus, most examples in this section show configuration inside a Spring container.

Spring은 데이터 접근 애플리케이션을 만들 때, 선택한 ORM 계층에 다양한 기능을 추가해줍니다. 개발자는 이 통합 기능을 필요한 만큼만 선택적으로 사용할 수 있으며, 이러한 통합 기능을 직접 구현했을 때의 비용이나 리스크와 비교해 보는 것이 좋습니다.

 

Spring의 ORM 지원은 기술에 상관없이 마치 일반 라이브러리를 사용하듯 활용할 수 있는데, 그 이유는 모든 기능이 재사용 가능한 JavaBean 형태로 설계되어 있기 때문입니다.

 

또한, Spring의 IoC 컨테이너 안에서 ORM을 사용하면 설정과 배포가 더 쉬워집니다. 그래서 이 섹션의 대부분 예제들은 Spring 컨테이너 내부에서 ORM을 설정하는 방식으로 설명됩니다.

 

The benefits of using the Spring Framework to create your ORM DAOs include:

Spring Framework를 사용해서 ORM DAO(Data Access Object)를 만들 때 얻을 수 있는 이점은 다음과 같습니다:

 

  • Easier testing. Spring’s IoC approach makes it easy to swap the implementations and configuration locations of Hibernate SessionFactory instances, JDBC DataSource instances, transaction managers, and mapped object implementations (if needed). This in turn makes it much easier to test each piece of persistence-related code in isolation.

더 쉬운 테스트

Spring의 IoC(제어의 역전) 방식 덕분에, Hibernate의 SessionFactory, JDBC의 DataSource, 트랜잭션 매니저, 그리고 매핑된 객체 구현체들을 손쉽게 교체할 수 있습니다.

 

이런 유연성 덕분에, 각각의 영속성(persistence) 관련 코드들을 독립적으로 분리해서 테스트하는 것이 훨씬 수월해집니다.

 

즉, 복잡한 설정을 매번 다시 할 필요 없이 원하는 컴포넌트만 바꿔서 테스트할 수 있는 구조가 마련된다는 뜻입니다.

 

  • Common data access exceptions. Spring can wrap exceptions from your ORM tool, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This feature lets you handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches, throws, and exception declarations. You can still trap and handle exceptions as necessary. Remember that JDBC exceptions (including DB-specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.

공통 데이터 접근 예외 처리 기능

Spring은 JPA나 Hibernate 같은 ORM 도구에서 발생하는 예외를 자체적으로 감싸서, 각 도구에 특화된 예외(checked exception 포함)를 공통된 런타임 예외 계층인 DataAccessException 계열로 변환해줍니다.

 

이 덕분에 대부분의 복구 불가능한 예외를 불필요하게 catchthrows, 예외 선언으로 코드를 복잡하게 만들지 않고도, 알맞은 계층에서만 처리할 수 있게 됩니다.

 

필요하다면 특정 예외만 따로 잡아 처리할 수도 있고, JDBC를 사용하는 경우에도 데이터베이스 벤더별 예외를 포함해 동일한 예외 계층 구조로 변환되기 때문에, JDBC 작업도 통일된 프로그래밍 모델 안에서 일관되게 처리할 수 있습니다.

 

  • General resource management. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, and other related resources. This makes these values easy to manage and change. Spring offers efficient, easy, and safe handling of persistence resources. For example, related code that uses Hibernate generally needs to use the same Hibernate Session to ensure efficiency and proper transaction handling. Spring makes it easy to create and bind a Session to the current thread transparently, by exposing a current Session through the Hibernate SessionFactory. Thus, Spring solves many chronic problems of typical Hibernate usage, for any local or JTA transaction environment.

일반적인 리소스 관리

Spring의 ApplicationContext는 Hibernate의 SessionFactory, JPA의 EntityManagerFactory, JDBC의 DataSource 같은 영속성 관련 리소스들의 위치와 설정을 중앙에서 통합 관리할 수 있습니다.

이렇게 하면 해당 리소스를 설정하거나 바꾸기가 훨씬 쉬워지고, 관리 또한 간편해집니다.

 

Spring은 이러한 영속성 리소스를 효율적이고 안전하며 간단하게 다룰 수 있도록 도와줍니다.

예를 들어 Hibernate를 사용할 때는 같은 트랜잭션 내에서는 동일한 Session을 공유해야 성능과 트랜잭션 관리가 제대로 동작합니다.

 

Spring은 이를 위해, SessionFactory에서 현재 쓰레드에 바인딩된 Session을 자동으로 제공해주는 기능을 지원합니다. 개발자는 따로 신경 쓰지 않아도 같은 세션이 유지되도록 해주는 것이죠.

 

결과적으로 Spring은 로컬 트랜잭션이든, JTA 기반 트랜잭션 환경이든 상관없이, Hibernate를 사용할 때 자주 발생하는 문제들을 대부분 해결해줍니다.

 

  • Integrated transaction management. You can wrap your ORM code with a declarative, aspect-oriented programming (AOP) style method interceptor either through the @Transactional annotation or by explicitly configuring the transaction AOP advice in an XML configuration file. In both cases, transaction semantics and exception handling (rollback and so on) are handled for you. As discussed in Resource and Transaction Management, you can also swap various transaction managers, without affecting your ORM-related code. For example, you can swap between local transactions and JTA, with the same full services (such as declarative transactions) available in both scenarios. Additionally, JDBC-related code can fully integrate transactionally with the code you use to do ORM. This is useful for data access that is not suitable for ORM (such as batch processing and BLOB streaming) but that still needs to share common transactions with ORM operations.

통합된 트랜잭션 관리

Spring에서는 ORM 코드에 대해 선언적이고 AOP(관점 지향 프로그래밍) 방식의 트랜잭션 처리를 적용할 수 있습니다.

이는 @Transactional 어노테이션을 사용하거나, XML 설정 파일에서 트랜잭션 AOP 설정을 명시적으로 지정하는 방식으로 이뤄집니다.

어떤 방법을 사용하든, 트랜잭션의 시작·커밋·롤백 같은 처리는 Spring이 자동으로 처리해줍니다.

 

또한 리소스 및 트랜잭션 관리에서 설명했듯, 트랜잭션 매니저를 변경하더라도 ORM 코드에는 영향을 주지 않습니다.

예를 들어, 로컬 트랜잭션과 JTA 간 전환도 무리 없이 가능하며, 두 방식 모두에서 선언적 트랜잭션 기능을 동일하게 사용할 수 있습니다.

 

그리고 JDBC 관련 코드도 ORM과 동일한 트랜잭션 안에서 함께 동작할 수 있습니다.

이건 특히 ORM으로 처리하기 어려운 작업(예: 대용량 배치 처리나 BLOB 스트리밍)에도 동일한 트랜잭션을 공유하게 만들 수 있어, 유용합니다.

 

 

 

정리

  • Spring은 JPA와 Hibernate를 위한 강력한 통합 지원을 제공하며, 설정은 DI를 통해 처리하고 공통 예외 계층을 따릅니다.
  • ORM 통합 기능은 필요한 만큼만 선택적으로 사용할 수 있고, 설정은 JavaBean 기반으로 구성되어 있습니다.
  • IoC 기반의 설정으로 컴포넌트를 쉽게 교체할 수 있어, ORM 테스트가 용이합니다.
  • Spring은 ORM 예외를 공통 런타임 예외(DataAccessException)으로 변환해주어 일관된 방식으로 예외 처리가 가능합니다.
  • ApplicationContext가 ORM 리소스를 중앙에서 관리하며, 동일한 세션을 쓰레드에 바인딩하여 효율적인 트랜잭션 처리를 돕습니다.
  • @Transactional 등을 통해 선언적 트랜잭션 처리가 가능하고, JDBC와 ORM 간 트랜잭션 통합도 지원됩니다.