0

I want to insert some data in a table of database after the SessionFactory of spring hibernate has been created.

I have a CUSTOMER table and I want to insert a particular Customer into this table if the Customer doesn't exist.

This is the configuration of SessionFactory:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="packagesToScan" value="com.edfx.adb.persist.entity" />
    <property name="entityInterceptor" ref="entityInterceptor" />
</bean>

I know that there is an option hibernate.hbm2ddl.import_files from which we can mention a sql file and the query will be executed at the time of SessionFactory initialization. But I don't want to follow this way.

Also I have found that we can use ServletContextListener for this kind of purpose, but I am not sure this is a good way to achieve what I want. Because what I understand is the listener will be initialized after deployment of war file, when the first user hit the application. So if I have a Scheduler which operates of the Customer and if the Scheduler get executed before any user hit the app, then the Scheduler wouldn't find that need-to-be-insert data.

Any pointer would be very helpful to me.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
  • Just create another method and inject the session object in it to call saveOrUpdate or save( will return the unique primary key) and if the update is successful add the session to the sessionFactory level cache (Level 2) cache.. also refresh your session factory .. you should be just fine... – KDjava Jan 06 '13 at 08:17
  • @KDjava I don't clearly understand your suggestion. By create a method what do you mean? Where to create the method? Are you suggesting to create a bean and define a method in that bean and call the method? Also the rest of the portion is not very clear, add session, refresh sessionFactory. Why do I need these? – Tapas Bose Jan 06 '13 at 11:35

1 Answers1

1

You can extend org.springframework.orm.hibernate4.LocalSessionFactoryBean and override buildSessionFactory() method to according to your requirement.

Avinash T.
  • 2,280
  • 2
  • 16
  • 23
  • Thanks for quick reply. I didn't find `afterSessionFactoryCreation` method in http://static.springsource.org/spring/docs/3.1.0.RC1/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBean.html! – Tapas Bose Jan 06 '13 at 06:42
  • @TapasBose- Updated the answer, It is not present in org.springframework.orm.hibernate4.LocalSessionFactoryBean – Avinash T. Jan 06 '13 at 06:49