[java] Hibernate에서 데이터베이스 연결 설정 방법은?
- Maven Dependency 추가:
먼저 프로젝트의 의존성 관리 도구인 Maven을 사용한다면,
pom.xml
파일에 Hibernate의 의존성을 추가해야 합니다. 아래 코드는 Hibernate 5.4.32.Final 버전을 사용하는 예시입니다.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.32.Final</version>
</dependency>
- Hibernate 설정 파일 추가:
Hibernate를 사용하기 위해
hibernate.cfg.xml
또는hibernate.properties
파일을 프로젝트에 추가해야 합니다. 이 파일은 데이터베이스 연결 정보 및 Hibernate의 다양한 설정을 포함합니다.
hibernate.cfg.xml
파일을 사용하는 경우, 프로젝트의 클래스 패스에 위치시킵니다.hibernate.properties
파일을 사용하는 경우, 프로젝트의 클래스 패스 또는 프로젝트의 루트 디렉토리에 위치시킵니다.
- 데이터베이스 연결 정보 설정:
hibernate.cfg.xml
또는hibernate.properties
파일에서 데이터베이스 연결 정보를 설정해야 합니다. 일반적으로 사용되는 설정은 다음과 같습니다.
- 드라이버 클래스:
hibernate.connection.driver_class
- DB URL:
hibernate.connection.url
- 사용자 이름:
hibernate.connection.username
- 비밀번호:
hibernate.connection.password
- 데이터베이스 dialect:
hibernate.dialect
아래는 hibernate.cfg.xml
파일에서 데이터베이스 연결 정보를 설정하는 예시입니다.
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">myusername</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
- Hibernate 세션 팩토리 생성:
Hibernate의 핵심인 세션 팩토리를 생성해야 합니다. 세션 팩토리는 데이터베이스와의 연결을 관리하며, 세션을 생성하는 역할을 합니다. 아래 코드는
hibernate.cfg.xml
파일을 사용하여 세션 팩토리를 생성하는 예시입니다.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration();
sessionFactory = configuration.configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
위 코드에서 configure()
메소드를 호출하면 Hibernate는 hibernate.cfg.xml
파일을 찾아 사용합니다. 세션 팩토리를 필요로 하는 부분에서 HibernateUtil.getSessionFactory()
를 호출하여 세션 팩토리를 얻을 수 있습니다.
이제 Hibernate를 사용하여 데이터베이스와의 연결 설정이 완료되었습니다. Hibernate의 강력한 ORM 기능을 활용하여 자바 애플리케이션에서 데이터베이스를 다룰 수 있습니다.
더 자세한 내용을 알고 싶다면 Hibernate 공식 문서(https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html)를 참고하시기 바랍니다.