본문 바로가기

Development/Web & Server

[Spring Framework] Hibernate 4 연동하기

1. 라이브러리 추가하기~! (Pom.xml )


  <dependency>

            <groupId>org.hibernate</groupId>

            <artifactId>hibernate-core</artifactId>

            <version>4.2.8.Final</version>

        </dependency>



2. 하이버네이트 설정 아래와 같은 설정을 추가해줍니다.


<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">

        <property name="paramName" value="lang" />

    </bean>


    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">

        <property name="defaultLocale" value="ko" />

    </bean>


    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"

        p:location="classpath:hibernate/local_db.properties" />


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

    <property name="driverClassName" value="${jdbc.driverClassName}" />

    <property name="url" value="${jdbc.url}" />

    <property name="username" value="${jdbc.username}" />

    <property name="password" value="${jdbc.password}" />

<property name="validationQuery" value="SELECT 1" />

        <property name="testOnBorrow" value="true" />

    </bean>


    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire="byName">

        

        <property name="dataSource" ref="dataSource"/>

        <property name="packagesToScan" value="모델패키지!!"/>

        

        <property name="hibernateProperties">

            <props>

                <prop key="hibernate.dialect">${jdbc.dialect}</prop>

                <prop key="hibernate.show_sql">true</prop>                

            </props>

            

        </property>


    </bean>

    

    <!-- Transaction -->

    

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory" />

    </bean>

    

    <bean id="persistenceExceptionTranslationPostProcessor" 

    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>


     <tx:annotation-driven transaction-manager="transactionManager"/>


3. 위에 설정파일중에 local_db.properties 라고 파일을 연동하였는데 임의로 이름을 변경을 하거나 다음 이름과 같은 파일을 만들고


jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.dialect=org.hibernate.dialect.MySQLDialect

jdbc.url=jdbc:mysql://DB 주소?autoReconnect=true&interactiveClient=true&autoReconnectForPools=true

jdbc.username=

jdbc.password=


4. web.xml 파일에


<!-- Hibernate -->

<filter>

<filter-name>HibernateSession</filter-name>

<filter-class>

org.springframework.orm.hibernate4.support.OpenSessionInViewFilter

</filter-class>

</filter>

<filter-mapping>

<filter-name>HibernateSession</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>


5. 2번의에서 모델 패키지를 선언하시고 해당 패키지 경로에 모델클래스를 만듭니다.

예 시


@Entity

@Table (name = "action")

public class Action {

public int getmId() {

return mId;

}


public void setmId(int mId) {

this.mId = mId;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


@Override

public String toString() {

return "Action [mId=" + mId + ", name=" + name + "]";

}


//Variables

@Id

@Column (name = "id")

@GeneratedValue

private Integer mId;

@Column(name = "name")

private String name;


}//end Action Method


6. 사용법 (하이버네이트3 에서 쓰는것 과 같이 똑같이 사용하면된다.~!)


@Inject private SessionFactory sessionFactory;


함수에서...

Action object = ~~~~~~~;

this.mSessionFactory.getCurrentSession().save(object);


final Query query = this.mSessionFactory.getCurrentSession().createQuery("FROM " + 클래스 이름..);

query.list();