하이버네이트 인터뷰 질문과 답변

Hibernate는 Java 애플리케이션의 가장 널리 사용되는 ORM 도구 중 하나입니다. 데이터베이스 작업에 대한 기업 애플리케이션에서 많이 사용됩니다. 그래서 인터뷰 전에 지식을 되짚기 위해 하이버네이트 인터뷰 질문에 대한 포스트를 쓰기로 결정했습니다. 신입이든 경험이 있는 개발자이든, Hibernate ORM 도구에 대한 좋은 지식을 가지고 있는 것이 인터뷰에서 성공하기에 도움이 됩니다. 여기서 중요한 하이버네이트 인터뷰 질문과 그에 대한 답변을 제공하여 지식을 되짚고 인터뷰어에게 좋은 인상을 남길 수 있도록 도와드리겠습니다. 다른 인터뷰 질문 포스트와 마찬가지로, 나중에 이 목록에 더 많은 질문을 추가할 가능성이 있으므로 나중에 참고할 수 있도록 이를 북마크해두는 것이 좋습니다. 최근에 하이버네이트에 관한 많은 포스트를 썼는데, 대부분의 포스트에는 완전한 다운로드 가능한 프로젝트가 포함되어 있습니다. 필요할 때마다 그들에 대한 참고 자료를 제공할 것이고, 지식을 되짚기 위해 그것들을 살펴볼 수 있습니다.

하이버네이트 인터뷰 질문

  1. 하이버네이트 프레임워크란?
  2. Java Persistence API (JPA)란 무엇인가요?
  3. 하이버네이트 프레임워크를 사용하는 것의 중요한 이점은 무엇인가요?
  4. Hibernate가 JDBC보다 가지는 장점은 무엇입니까?
  5. Hibernate 프레임워크의 중요한 인터페이스를 몇 가지 말해주세요.
  6. Hibernate 구성 파일이 무엇입니까?
  7. Hibernate 매핑 파일이 무엇입니까?
  8. Hibernate 매핑에 사용되는 중요한 주석을 몇 가지 말해주세요.
  9. Hibernate SessionFactory가 무엇이며 어떻게 구성합니까?
  10. Hibernate SessionFactory는 스레드 안전합니까?
  11. Hibernate Session이 무엇이며 어떻게 얻습니까?
  12. Hibernate Session은 스레드 안전합니까?
  13. openSession과 getCurrentSession의 차이점은 무엇입니까?
  14. Hibernate Session get()과 load() 메서드의 차이점은 무엇입니까?
  15. Hibernate 캐싱이 무엇이며 Hibernate 첫 번째 레벨 캐시를 설명해주세요.
  16. EHCache를 사용하여 Hibernate 두 번째 레벨 캐시를 구성하는 방법은 무엇입니까?
  17. 엔터티 빈의 다른 상태는 무엇입니까?
  18. Hibernate Session merge() 호출의 용도는 무엇입니까?
  19. Hibernate save(), saveOrUpdate() 및 persist() 메서드의 차이점은 무엇입니까?
  20. Entity 빈에 no-args 생성자가 없으면 어떻게 될까요?
  21. 정렬된 컬렉션과 순서가 지정된 컬렉션의 차이점은 무엇이며, 어떤 것이 더 나은가요?
  22. Hibernate에서의 컬렉션 유형은 무엇인가요?
  23. Hibernate에서 조인을 어떻게 구현하나요?
  24. Entity 클래스를 final로 만들면 안 되는 이유는 무엇인가요?
  25. HQL이란 무엇이며, 어떤 이점이 있나요?
  26. Hibernate의 Query Cache는 무엇인가요?
  27. Hibernate에서 원시 SQL 쿼리를 실행할 수 있나요?
  28. Hibernate에서 원시 SQL 쿼리 지원의 이점은 무엇인가요?
  29. Named SQL Query란 무엇인가요?
  30. Named SQL Query의 이점은 무엇인가요?
  31. Hibernate Criteria API의 이점은 무엇인가요?
  32. 로그 파일에 Hibernate에서 생성된 SQL 쿼리를 기록하는 방법은 무엇인가요?
  33. Hibernate Proxy가 무엇이며, lazy loading에 어떻게 도움이 되나요?
  34. Hibernate에서 관계를 어떻게 구현하나요?
  35. Hibernate에서 트랜잭션 관리는 어떻게 작동하나요?
  36. 캐스케이딩이란 무엇이며 캐스케이딩의 다양한 유형은 무엇인가요?
  37. 하이버네이트 응용 프로그램에 log4j 로깅을 통합하는 방법은 무엇인가요?
  38. 어떻게 어플리케이션 서버 JNDI DataSource를 Hibernate 프레임워크와 함께 사용하나요?
  39. 하이버네이트와 스프링 프레임워크를 어떻게 통합하나요?
  40. HibernateTemplate 클래스는 무엇인가요?
  41. 하이버네이트를 서블릿 또는 Struts2 웹 애플리케이션과 어떻게 통합하나요?
  42. 하이버네이트 프레임워크에서 사용되는 디자인 패턴은 무엇인가요?
  43. 하이버네이트 프레임워크에서 따를 수 있는 최상의 실천 방법은 무엇인가요?
  44. 하이버네이트 Validator 프레임워크란 무엇인가요?
  45. 하이버네이트 Tools Eclipse 플러그인의 혜택은 무엇인가요?

하이버네이트 인터뷰 질문과 답변

  1. Hibernate Framework이란 무엇인가요?

    객체-관계 매핑 또는 ORM은 응용 프로그램 도메인 모델 객체를 관계형 데이터베이스 테이블에 매핑하는 프로그래밍 기술입니다. Hibernate는 응용 프로그램 도메인 객체를 관계형 데이터베이스 테이블에 매핑하고 그 반대도 제공하는 Java 기반 ORM 도구입니다. Hibernate는 Java Persistence API의 참조 구현을 제공하여 느슨한 결합의 이점을 가진 ORM 도구로서의 우수한 선택지가 됩니다. Hibernate 영속성 API를 사용하여 CRUD 작업을 수행할 수 있습니다. Hibernate 프레임워크는 JPA 주석 및 XML 기반 구성을 사용하여 일반적인 자바 객체를 전통적인 데이터베이스 테이블에 매핑할 수 있는 옵션을 제공합니다. 마찬가지로 Hibernate 구성은 XML 구성 파일 및 프로그래밍 방식으로 유연하게 수행할 수 있습니다. Hibernate 프레임워크 사용에 대한 간단한 개요는 Hibernate 초보자 튜토리얼을 참조하십시오.

  2. Java Persistence API (JPA)란?

    Java Persistence API (JPA)는 응용 프로그램에서 관계형 데이터를 관리하기 위한 명세를 제공합니다. 현재 JPA 버전 2.1은 2011년 7월에 JSR 338로 시작되었습니다. JPA 2.1은 2013년 5월 22일에 최종으로 승인되었습니다. JPA 사양은 javax.persistence 패키지의 주석을 사용하여 정의됩니다. JPA 주석을 사용하면 구현 독립적인 코드를 작성할 수 있습니다.

  3. 하이버네이트 프레임워크를 사용하는 중요한 이점은 무엇입니까?

    하이버네이트 프레임워크를 사용하는 중요한 이점은 다음과 같습니다:

    1. 하이버네이트는 JDBC와 함께 제공되는 보일러플레이트 코드를 모두 제거하고 리소스 관리를 처리하여 비즈니스 로직에 집중할 수 있습니다.
    2. 하이버네이트 프레임워크는 XML 및 JPA 주석을 지원하여 코드 구현이 독립적이 되도록 합니다.
    3. 하이버네이트는 SQL과 유사한 강력한 쿼리 언어인 HQL을 제공합니다. 그러나 HQL은 완전히 객체지향적이며 상속, 다형성 및 연관성과 같은 개념을 이해합니다.
    4. 하이버네이트는 레드햇 커뮤니티의 오픈 소스 프로젝트로 전 세계적으로 사용됩니다. 이는 학습 곡선이 낮고 온라인 문서가 풍부하며 포럼에서 쉽게 도움을 얻을 수 있기 때문에 다른 것보다 나은 선택입니다.
    5. 하이버네이트는 다른 자바 EE 프레임워크와 쉽게 통합됩니다. Spring Framework에서는 하이버네이트를 Spring 애플리케이션과 내장 지원으로 통합할 수 있습니다.
    6. 하이버네이트는 프록시 객체를 사용하여 지연 초기화를 지원하며 실제 데이터베이스 쿼리는 필요할 때만 수행됩니다.
    7. 하이버네이트 캐시는 성능 향상에 도움이 됩니다.
    8. 데이터베이스 공급 업체별 기능에 대해서는 하이버네이트가 적합하며 네이티브 SQL 쿼리를 실행할 수도 있습니다. 전반적으로 하이버네이트는 ORM 도구로 현재 시장에서 최고의 선택입니다. ORM 도구에서 필요한 모든 기능을 갖추고 있습니다.
  4. Hibernate의 JDBC 대비 장점은 무엇입니까?

    Hibernate 프레임워크의 중요한 장점 중 일부는 다음과 같습니다:

    1. Hibernate는 JDBC API와 함께 제공되는 많은 보일러플레이트 코드를 제거하여 코드가 더 깨끗하고 가독성 있게 보입니다.
    2. Hibernate는 상속, 연관 및 컬렉션을 지원합니다. 이러한 기능은 JDBC API에는 없습니다.
    3. Hibernate는 암시적으로 트랜잭션 관리를 제공하며, 사실 대부분의 쿼리는 트랜잭션 외부에서 실행될 수 없습니다. JDBC API에서는 commit 및 rollback을 사용하여 트랜잭션 관리 코드를 작성해야 합니다. JDBC 트랜잭션 관리에서 자세히 읽어보십시오.
    4. JDBC API는 확인된 예외인 SQLException을 throw하므로 많은 try-catch 블록 코드를 작성해야 합니다. 대부분의 경우 매번 JDBC 호출마다 중복되며 트랜잭션 관리에 사용됩니다. Hibernate는 JDBC 예외를 래핑하여 JDBCException 또는 HibernateException이 확인되지 않은 예외를 throw하므로 처리할 코드를 작성할 필요가 없습니다. Hibernate 내장 트랜잭션 관리는 try-catch 블록의 사용을 제거합니다.
    5. Hibernate 쿼리 언어(HQL)는 객체 지향적이며 Java 프로그래밍 언어에 가깝습니다. JDBC의 경우 네이티브 SQL 쿼리를 작성해야 합니다.
    6. Hibernate는 성능을 위해 캐싱을 지원합니다. JDBC 쿼리는 캐시되지 않으므로 성능이 낮습니다.
    7. Hibernate는 데이터베이스 테이블도 생성할 수 있는 옵션을 제공합니다. JDBC에서는 테이블이 데이터베이스에 존재해야 합니다.
    8. Hibernate 구성은 JDBC와 마찬가지로 JNDI DataSource를 사용하여 연결 풀을 사용할 수 있도록 도와줍니다. 이는 기업 애플리케이션에서 매우 중요한 기능이며 JDBC API에는 완전히 없습니다.
    9. Hibernate는 JPA 주석을 지원하므로 코드가 구현과 독립적이며 다른 ORM 도구로 쉽게 대체할 수 있습니다. JDBC 코드는 애플리케이션과 매우 강하게 결합되어 있습니다.
  5. 하이버네이트 프레임워크의 중요한 인터페이스를 몇 가지 말해주세요?

Some of the important interfaces of Hibernate framework are:
1.  **SessionFactory (org.hibernate.SessionFactory)**: SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
2.  **Session (org.hibernate.Session)**: Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC `java.sql.Connection` and works as a factory for `org.hibernate.Transaction`. We should open session only when it's required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
3.  **Transaction (org.hibernate.Transaction)**: Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
  1. 하이버네이트 구성 파일이란 무엇인가요?

Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
  1. 하이버네이트 매핑 파일이란 무엇인가요?

Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can't use annotations.
  1. 하이버네이트 매핑에 사용되는 몇 가지 중요한 주석을 언급해 주세요.

Hibernate supports JPA annotations and it has some other annotations in `org.hibernate.annotations` package. Some of the important JPA and hibernate annotations used are:

1.  **javax.persistence.Entity**: Used with model classes to specify that they are entity beans.
2.  **javax.persistence.Table**: Used with entity beans to define the corresponding table name in database.
3.  **javax.persistence.Access**: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
4.  **javax.persistence.Id**: Used to define the primary key in the entity bean.
5.  **javax.persistence.EmbeddedId**: Used to define composite primary key in the entity bean.
6.  **javax.persistence.Column**: Used to define the column name in database table.
7.  **javax.persistence.GeneratedValue**: Used to define the strategy to be used for generation of primary key. Used in conjunction with `javax.persistence.GenerationType` enum.
8.  **javax.persistence.OneToOne**: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as `OneToMany`, `ManyToOne` and `ManyToMany`
9.  **org.hibernate.annotations.Cascade**: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with `org.hibernate.annotations.CascadeType`
10.  **javax.persistence.PrimaryKeyJoinColumn**: Used to define the property for foreign key. Used with `org.hibernate.annotations.GenericGenerator` and `org.hibernate.annotations.Parameter`

Here are two classes showing usage of these annotations.

```
package com.journaldev.hibernate.model;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;

@Entity
@Table(name = "EMPLOYEE")
@Access(value=AccessType.FIELD)
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "emp_id")
	private long id;

	@Column(name = "emp_name")
	private String name;

	@OneToOne(mappedBy = "employee")
	@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
	private Address address;

	//getter setter 메서드
}
```

```
package com.journaldev.hibernate.model;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {

	@Id
	@Column(name = "emp_id", unique = true, nullable = false)
	@GeneratedValue(generator = "gen")
	@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
	private long id;

	@Column(name = "address_line1")
	private String addressLine1;

	@OneToOne
	@PrimaryKeyJoinColumn
	private Employee employee;

	//getter setter 메서드
}
```
  1. 하이버네이트 SessionFactory란 무엇이며 어떻게 구성합니까?

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.
  1. 하이버네이트 SessionFactory는 스레드로부터 안전합니까?

Internal state of SessionFactory is immutable, so it's thread safe. Multiple threads can access it simultaneously to get Session instances.
  1. Hibernate Session은 무엇이며 어떻게 얻을 수 있나요?

Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction. Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.
  1. Hibernate Session은 스레드 안전한가요?

Hibernate Session object is not thread safe, every thread should get it's own session instance and close it after it's work is finished.
  1. openSession과 getCurrentSession의 차이는 무엇입니까?

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed.

```
<property name="hibernate.current_session_context_class">thread</property>
```

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment. There is another method openStatelessSession() that returns stateless session, for more details with examples please read [Hibernate openSession vs getCurrentSession](/community/tutorials/hibernate-sessionfactory).
  1. Hibernate Session의 get()과 load() 메서드의 차이는 무엇입니까?

Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.

1.  get() loads the data as soon as it's called whereas load() returns a proxy object and loads data only when it's actually required, so load() is better because it support lazy loading.
2.  Since load() throws exception when data is not found, we should use it only when we know data exists.
3.  We should use get() when we want to make sure data exists in the database.

For clarification regarding the differences, please read [Hibernate get vs load](/community/tutorials/hibernate-session-get-vs-load-difference-with-examples).
  1. 하이버네이트 캐싱이란 무엇인가요? 먼저 하이버네이트 일급 캐시를 설명해주세요?

As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost. For better explanation, please read [Hibernate First Level Cache](/community/tutorials/hibernate-caching-first-level-cache).
  1. EHCache를 사용하여 하이버네이트 두 번째 단계 캐시를 구성하는 방법은 무엇인가요?

EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.
-   Add hibernate-ehcache dependency in your maven project, if it's not maven then add corresponding jars.
    
    ```
    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.3.5.Final</version>
    </dependency>
    ```
    
-   Add below properties in hibernate configuration file.
    
    ```
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
             
    <!-- For singleton factory -->
    <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
    -->
              
    <!-- enable second level cache and query cache -->
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
    ```
    
-   Create EHCache configuration file, a sample file myehcache.xml would look like below.
    
    ```
    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
        monitoring="autodetect" dynamicConfig="true">
     
        <diskStore path="java.io.tmpdir/ehcache" />
     
        <defaultCache maxEntriesLocalHeap="10000" eternal="false"
            timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
            maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" statistics="true">
            <persistence strategy="localTempSwap" />
        </defaultCache>
     
        <cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
            timeToIdleSeconds="5" timeToLiveSeconds="10">
            <persistence strategy="localTempSwap" />
        </cache>
     
        <cache name="org.hibernate.cache.internal.StandardQueryCache"
            maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
            <persistence strategy="localTempSwap" />
        </cache>
     
        <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
            maxEntriesLocalHeap="5000" eternal="true">
            <persistence strategy="localTempSwap" />
        </cache>
    </ehcache>
    ```
    
-   Annotate entity beans with @Cache annotation and caching strategy to use. For example,
    
    ```
    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;
    
    @Entity
    @Table(name = "ADDRESS")
    @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
    public class Address {
    
    }
    ```
    
That's it, we are done. Hibernate will use the EHCache for second level caching, read [Hibernate EHCache Example](/community/tutorials/hibernate-ehcache-hibernate-second-level-cache) for a complete example with explanation.
  1. 엔터티 빈의 여러 상태는 무엇인가요?

An entity bean instance can exist is one of the three states.
1.  **Transient**: When an object is never persisted or associated with any session, it's in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().
2.  **Persistent**: When an object is associated with a unique session, it's in persistent state. Any instance returned by a get() or load() method is persistent.
3.  **Detached**: When an object is previously persistent but not associated with any session, it's in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().
  1. Hibernate 세션 merge() 호출의 용도는 무엇인가요?

Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked. For example program, read [Hibernate merge](/community/tutorials/hibernate-session-merge-vs-update-save-saveorupdate-persist-example).
  1. Hibernate의 save(), saveOrUpdate() 및 persist() 메서드의 차이는 무엇입니까?

Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately. Hibernate persist is similar to save with transaction. I feel it's better than save because we can't use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn't return the generated id immediately, so data persistence happens when needed. Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed. For example usage of these methods, read [Hibernate save vs persist](/community/tutorials/hibernate-session-merge-vs-update-save-saveorupdate-persist-example).
  1. Entity 빈에 무인자 생성자가 없으면 어떻게 됩니까?

Hibernate uses [Reflection API](/community/tutorials/java-reflection-example-tutorial) to create instance of Entity beans, usually when you call get() or load() methods. The method `Class.newInstance()` is used for this and it requires no-args constructor. So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get `HibernateException`.
  1. 정렬된 컬렉션과 순서가 지정된 컬렉션의 차이점은 무엇이며, 어떤 것이 더 나은가요?

When we use Collection API sorting algorithms to sort a collection, it's called sorted list. For small collections, it's not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement `Comparable` or `Comparator` interface for it to work, read more at [java object list sorting](/community/tutorials/comparable-and-comparator-in-java-example). If we are using Hibernate framework to load collection data from database, we can use it's Criteria API to use "order by" clause to get ordered list. Below code snippet shows you how to get it.

```
List<Employee> empList = session.createCriteria(Employee.class)
						.addOrder(Order.desc("id")).list();
```

Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn't cause memory issues.
  1. Hibernate에서 컬렉션 유형은 무엇인가요?

There are five collection types in hibernate used for one-to-many relationship mappings.
1.  Bag
2.  Set
3.  List
4.  Array
5.  Map
  1. Hibernate에서 조인을 구현하는 방법은 무엇입니까?

There are various ways to implement joins in hibernate.
-   Using associations such as one-to-one, one-to-many etc.
-   Using JOIN in the HQL query. There is another form "join fetch" to load associated data simultaneously, no lazy loading.
-   We can fire native sql query and use join keyword.
  1. 왜 Entity 클래스를 final로 만들지 말아야 합니까?

Hibernate use proxy classes for lazy loading of data, only when it's needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.
  1. HQL이란 무엇이며 그 이점은 무엇인가요?

Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming. Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE. The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However it's a better choice than native sql query because of Object-Oriented approach. Read more at [HQL Example](/community/tutorials/hibernate-query-language-hql-example-tutorial).
  1. Hibernate의 쿼리 캐시(Query Cache)란 무엇인가요?

Hibernate implements a cache region for queries resultset that integrates closely with the hibernate second-level cache. This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters. First of all we need to configure below property in hibernate configuration file.

```
<property name="hibernate.cache.use_query_cache">true</property>
```

And in code, we need to use setCacheable(true) method of Query, quick example looks like below.

```
Query query = session.createQuery("from Employee");
query.setCacheable(true);
query.setCacheRegion("ALL_EMP");
```
  1. 우리는 하이버네이트에서 네이티브 SQL 쿼리를 실행할 수 있나요?

Hibernate provide option to execute native SQL queries through the use of `SQLQuery` object. For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching. Read more at [Hibernate Native SQL Query Example](/community/tutorials/hibernate-native-sql-query-example).
  1. 하이버네이트에서 네이티브 SQL 쿼리 지원의 장점은 무엇입니까?

Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.
  1. Named SQL Query란 무엇인가요?

Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL. Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.
  1. Named SQL Query의 이점은 무엇인가요?

Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code. Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries. Hibernate Named Query is global, means once defined it can be used throughout the application. However one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.
  1. Hibernate Criteria API의 이점은 무엇인가요?

Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach. Some of the common usage of Criteria API are:

-   Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
-   Criteria API can be used with ProjectionList to fetch selected columns only.
-   Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
-   Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
-   Criteria API provides addOrder() method that we can use for ordering the results.

Learn some quick examples at [Hibernate Criteria Example](/community/tutorials/hibernate-criteria-example-tutorial).
  1. 로그 파일에 하이버네이트에서 생성된 SQL 쿼리를 기록하는 방법은 무엇인가요?

We can set below property for hibernate configuration to log SQL queries.

```
        <property name="hibernate.show_sql">true</property>
```

However we should use it only in Development or Testing environment and turn it off in production environment.
  1. 하이버네이트 프록시란 무엇이며, 게으른 로딩에 어떻게 도움이 되나요?

Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn't load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.
  1. Hibernate에서 관계를 구현하는 방법은 무엇인가요?

We can easily implement one-to-one, one-to-many and many-to-many relationships in hibernate. It can be done using JPA annotations as well as XML based configurations. For better understanding, you should go through following tutorials.
1.  [Hibernate One to One Mapping](/community/tutorials/hibernate-one-to-one-mapping-example-annotation)
2.  [Hibernate One to Many Mapping](/community/tutorials/hibernate-one-to-many-mapping-annotation)
3.  [Hibernate Many to Many Mapping](/community/tutorials/hibernate-many-to-many-mapping-join-tables)
  1. Hibernate에서 트랜잭션 관리가 어떻게 작동하나요?

Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session `beginTransaction()` to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction. Overall hibernate transaction management is better than JDBC transaction management because we don't need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.
  1. 카스케이딩이란 무엇이며, 카스케이딩의 다양한 유형은 무엇인가요?

When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it. Here is a simple example of applying cascading between primary and secondary entities.

```
import org.hibernate.annotations.Cascade;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;

}
```

Note that Hibernate CascadeType enum constants are little bit different from JPA `javax.persistence.CascadeType`, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example. Commonly used cascading types as defined in CascadeType enum are:
1.  None: No Cascading, it's not a type but when we don't define any cascading then no operations in parent affects the child.
2.  ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
3.  SAVE\_UPDATE: Cascades save and update, available only in hibernate.
4.  DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
5.  DETATCH, MERGE, PERSIST, REFRESH and REMOVE - for similar operations
6.  LOCK: Corresponds to the Hibernate native LOCK action.
7.  REPLICATE: Corresponds to the Hibernate native REPLICATE action.
  1. 하이버네이트 애플리케이션에 log4j 로깅을 통합하는 방법은 무엇인가요?

Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.

-   Add log4j dependencies for maven project, if not maven then add corresponding jar files.
-   Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step.
-   For standalone projects, use static block to configure log4j using `DOMConfigurator` or `PropertyConfigurator`. For web applications, you can use ServletContextListener to configure it.

That's it, our setup is ready. Create `org.apache.log4j.Logger` instance in the java classes and start logging. For complete example code, you should go through [Hibernate log4j example](/community/tutorials/hibernate-log4j-logging) and [Servlet log4j example](/community/tutorials/servlet-jdbc-database-connection-example).
  1. 하이버네이트 프레임워크에서 애플리케이션 서버 JNDI 데이터 소스를 사용하는 방법은 무엇인가요?

For web applications, it's always best to allow servlet container to manage the connection pool. That's why we define JNDI resource for DataSource and we can use it in the web application. It's very easy to use in Hibernate, all we need is to remove all the database specific properties and use below property to provide the JNDI DataSource name.

```
<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>
```

For a complete example, go through [Hibernate JNDI DataSource Example](/community/tutorials/hibernate-tomcat-jndi-datasource-example-tutorial).
  1. 하이버네이트와 스프링 프레임워크를 통합하는 방법은 무엇인가요?

Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part with using Spring is that it provides out-of-box integration support for Hibernate with **Spring ORM** module. Following steps are required to integrate Spring and Hibernate frameworks together.

1.  Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
2.  Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
3.  If you are using Hibernate 3, you need to configure `org.springframework.orm.hibernate3.LocalSessionFactoryBean` or `org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean` in Spring Bean configuration file. For Hibernate 4, there is single class `org.springframework.orm.hibernate4.LocalSessionFactoryBean` that should be configured.
4.  Note that we don't need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using `@Transactional` annotation.

For complete example go through [Spring Hibernate Integration](/community/tutorials/spring-hibernate-integration-example-tutorial) and [Spring MVC Hibernate Integration](/community/tutorials/spring-mvc-hibernate-mysql-integration-crud-example-tutorial).
  1. HibernateTemplate 클래스란 무엇인가요?

When Spring and Hibernate integration started, Spring ORM provided two helper classes - `HibernateDaoSupport` and `HibernateTemplate`. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However from Hibernate 3.0.1, we can use `SessionFactory` _getCurrentSession()_ method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that's why we should not use these classes anymore. One other benefit of `HibernateTemplate` was exception translation but that can be achieved easily by using `@Repository` annotation with service classes, shown in above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.
  1. Hibernate을 Servlet 또는 Struts2 웹 애플리케이션과 통합하는 방법은 무엇인가요?

Hibernate integration with Servlet or Struts2 needs to be done using `ServletContextListener`, a complete example can be found at [Hibernate Struts2 Integration Example](/community/tutorials/struts2-hibernate-integration-example-tutorial).
  1. Hibernate 프레임워크에서 사용되는 디자인 패턴은 무엇입니까?

Some of the design patterns used in Hibernate Framework are:
-   Domain Model Pattern - An object model of the domain that incorporates both behavior and data.
-   Data Mapper - A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
-   [Proxy Pattern](/community/tutorials/proxy-design-pattern) for lazy loading
-   [Factory pattern](/community/tutorials/factory-design-pattern-in-java "Factory Design Pattern in Java") in SessionFactory
  1. Hibernate 프레임워크에서 따라야 할 최상의 관행은 무엇입니까?

Some of the best practices to follow in Hibernate are:
-   Always check the primary key field access, if it's generated at the database layer then you should not have a setter for this.
-   By default hibernate set the field values directly, without using setters. So if you want hibernate to use setters, then make sure proper access is defined as `@Access(value=AccessType.PROPERTY)`.
-   If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
-   Use native sql query only when it can't be done using HQL, such as using database specific feature.
-   If you have to sort the collection, use ordered list rather than sorting it using Collection API.
-   Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity specific query, you can keep them in the entity bean itself.
-   For web applications, always try to use JNDI DataSource rather than configuring to create connection in hibernate.
-   Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
-   For collections, try to use Lists, maps and sets. Avoid array because you don't get benefit of lazy loading.
-   Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state.
-   Prefer DAO pattern for exposing the different methods that can be used with entity bean
-   Prefer lazy fetching for associations
  1. 하이버네이트 검증 프레임워크란 무엇인가요?

Data validation is integral part of any application. You will find data validation at presentation layer with the use of Javascript, then at the server side code before processing it. Also data validation occurs before persisting it, to make sure it follows the correct format. Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provides specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs. Read more at [Hibernate Validation Example](/community/tutorials/hibernate-validator-jsr303-example-tutorial).
  1. 하이버네이트 도구 이클립스 플러그인의 장점은 무엇인가요?

Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes before hand. Learn how to install and use at [Hibernate Tools Eclipse Plugin](/community/tutorials/hibernate-tools-eclipse-plugin).

이것이 하이버네이트 인터뷰 질문과 답변에 관한 모든 내용입니다. 신입자 또는 경험있는 개발자로서 인터뷰에 도움이 되기를 바랍니다. 여기서 빠뜨린 중요한 질문이 있다면 알려주세요. 추가하도록 하겠습니다.

Source:
https://www.digitalocean.com/community/tutorials/hibernate-interview-questions-and-answers