Java EE Hibernate 기본 설정 가이드

Hibernate는 자바 개발 고급 단계에서 필수적인 기술로, 자바 3대 프레임워크 중 하나로서 그 중요성이 매우 큽니다. 이 글에서는 Hibernate의 기본 설정 방법을 단계별로 설명하겠습니다. Hibernate는 데이터베이스와의 상호작용을 간편하게 만들어주며, 개발자가 더 효율적으로 데이터 영속성을 관리할 수 있도록 도와줍니다.

Hibernate는 오픈소스 객체 관계 매핑(ORM) 프레임워크로, JDBC를 가볍게 객체로 래핑하여 자바 개발자가 객체 지향 프로그래밍 사고로 데이터베이스를 조작할 수 있게 해줍니다. Hibernate는 JDBC를 사용하는 모든 환경에서 적용할 수 있으며, 자바 클라이언트 프로그램뿐만 아니라 Servlet/JSP 웹 애플리케이션에서도 사용할 수 있습니다. 특히 J2EE 아키텍처에서 EJB의 CMP를 대체하여 데이터 영속성 작업을 수행하는 데 혁신적인 역할을 합니다.

Hibernate의 핵심 인터페이스는 총 6개로, Session, SessionFactory, Transaction, Query, Criteria, Configuration이 있습니다. 이 인터페이스들은 개발 과정에서 필수적으로 사용되며, 지속성 객체의 저장 및 검색과 트랜잭션 제어를 가능하게 합니다.

1단계: Java EE 개발 환경 설치

Java EE 개발을 위해서는 Eclipse IDE가 필요합니다. Eclipse for Java EE Developers 버전을 공식 웹사이트에서 다운로드하여 설치합니다. 설치 과정은 매우 간단하며, 기본 설정으로 진행하면 됩니다.

2단계: 새 프로젝트 생성

Eclipse에서 새 프로젝트를 생성합니다. File > New > Project를 선택한 후, Dynamic Web Project를 선택합니다. 프로젝트 이름은 자바 명명 규칙에 맞게 지정합니다.

3단계: 필요한 JAR 파일 추가

Hibernate를 사용하기 위해 필요한 라이브러리 JAR 파일을 프로젝트에 추가해야 합니다. 주요 라이브러리로는 hibernate-core, hibernate-entitymanager, mysql-connector-java 등이 있습니다. 이 파일들은 Maven이나 Gradle을 사용하거나, 수동으로 프로젝트의 lib 폴더에 추가할 수 있습니다.

4단계: Hibernate 환경 변수 설정

hibernate.properties 파일을 생성하고 다음과 같이 설정합니다:


######################
### Query Language ###
######################

## define query language constants / function names
hibernate.query.substitutions yes 'Y', no 'N'

## select the classic query parser
#hibernate.query.factory_class org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

#################
### Platforms ###
#################

## MySQL
hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
hibernate.connection.driver_class com.mysql.cj.jdbc.Driver
hibernate.connection.url jdbc:mysql://localhost:3306/testdb
hibernate.connection.username dbuser
hibernate.connection.password dbpassword

#################################
### Hibernate Connection Pool ###
#################################
hibernate.connection.pool_size 1

###########################
### C3P0 Connection Pool ###
###########################
hibernate.c3p0.max_size 2
hibernate.c3p0.min_size 2
hibernate.c3p0.timeout 5000
hibernate.c3p0.max_statements 100
hibernate.c3p0.idle_test_period 3000
hibernate.c3p0.acquire_increment 2
hibernate.c3p0.validate false

##############################
### Miscellaneous Settings ###
##############################

## print all generated SQL to the console
#hibernate.show_sql true

## format SQL in log and console
hibernate.format_sql true

## add comments to the generated SQL
#hibernate.use_sql_comments true

## generate statistics
#hibernate.generate_statistics true

## auto schema export
hibernate.hbm2ddl.auto update

설명:

  • hibernate.dialect: 사용하는 MySQL 데이터베이스 버전을 지정합니다.
  • hibernate.format_sql: SQL 쿼리를 포맷팅하여 로그에 출력합니다.
  • hibernate.hbm2ddl.auto update: 애플리케이션 실행 시 데이터베이스 스키마를 자동으로 업데이트합니다.

5단계: User 객체 클래스 생성

Hibernate에서 데이터 조작은 객체를 통해 이루어지므로, 먼저 엔티티 클래스를 생성해야 합니다:


public class Member {
    private int id;
    private String username;
    private String password;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
}

6단계: Member.hbm.xml 파일 생성

객체 클래스와 데이터베이스 테이블을 매핑하기 위해 XML 매핑 파일을 생성합니다:






    
    <class name="Member" table="t_member">
        <id name="id" column="c_id">
            <generator class="native"/>
        </id>
        
        <property name="username" column="c_username" length="50"/>
        <property name="password" column="c_password" length="50"/>
    </class>



이 파일은 해당 클래스와 동일한 패키지에 위치해야 하며, 파일 이름은 규칙에 맞게 지정해야 합니다.

7단계: hibernate.cfg.xml 파일 설정

마지막으로 Hibernate 설정 파일을 생성합니다:






    
        
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
        <property name="hibernate.connection.username">dbuser</property>
        <property name="hibernate.connection.password">dbpassword</property>
        
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <mapping resource="com/example/entity/Member.hbm.xml"/>
        
    


여기까지 Hibernate 기본 설정이 완료되었습니다. 다음 글에서는 이 환경을 사용하여 실제 데이터베이스 작업을 수행하는 방법을 설명하겠습니다.

태그: Java EE hibernate ORM JDBC MySQL

7월 7일 16:32에 게시됨