user2798694
user2798694

Reputation: 1033

Configure hibernate in spring application

I have successfully configured hibernate and I can run transactions but only from the psvm of the DAO class. I want to configure it with my spring app using the same configuration file i.e. hibernate.cfg.xml.

How can I do this? Most tutorials I've read simply neglect the hibernate configuration file.

Upvotes: 0

Views: 312

Answers (2)

Gabriel Ruiu
Gabriel Ruiu

Reputation: 2803

The hibernate.cfg.xml file is specified for the LocalEntityManagerFactoryBean, along with your DataSource

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath*:META-INF/hibernate.cfg.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

Here you can find an example of a Spring XML configuration containing some Hibernate configuration

Upvotes: 0

user3145373 ツ
user3145373 ツ

Reputation: 8156

You can add this code to you xml file to configure hibernate.

<!-- Hibernate Related Configuration. -->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://192.168.1.9:5432/dbname"/>
        <property name="username" value="postgres"/>
        <property name="password" value="pwd"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.domain"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.generate_statistics">true</prop>
            </props>
        </property>
    </bean>

    <!-- Transaction Manager -->
    <bean id="txManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

Upvotes: 1

Related Questions