3

I am using spring framework and for database I am using hibernate.cfg.xml in the following way

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">false</property> 
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.lynas.test.Student" />
    </session-factory>
</hibernate-configuration>

Now is there any way to write this code in the java file. Like a bean or something??

3 Answers 3

2

The Answer is YES. from http://java.dzone.com/articles/springhibernate-application

package com.sivalabs.springmvc.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * @author SivaLabs
 *
 */
@Configuration
public class RepositoryConfig
{
    //${jdbc.driverClassName}
    @Value("${jdbc.driverClassName}")     private String driverClassName;
    @Value("${jdbc.url}")                 private String url;
    @Value("${jdbc.username}")             private String username;
    @Value("${jdbc.password}")             private String password;

    @Value("${hibernate.dialect}")         private String hibernateDialect;
    @Value("${hibernate.show_sql}")     private String hibernateShowSql;
    @Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto;

    @Bean()    
    public DataSource getDataSource()
    {
        DriverManagerDataSource ds = new DriverManagerDataSource();        
        ds.setDriverClassName(driverClassName);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);        
        return ds;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
    {
        HibernateTransactionManager htm = new HibernateTransactionManager();
        htm.setSessionFactory(sessionFactory);
        return htm;
    }

    @Bean
    @Autowired
    public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)
    {
        HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
        return hibernateTemplate;
    }

    @Bean
    public AnnotationSessionFactoryBean getSessionFactory()
    {
        AnnotationSessionFactoryBean asfb = new AnnotationSessionFactoryBean();
        asfb.setDataSource(getDataSource());
        asfb.setHibernateProperties(getHibernateProperties());        
        asfb.setPackagesToScan(new String[]{"com.sivalabs"});
        return asfb;
    }

    @Bean
    public Properties getHibernateProperties()
    {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", hibernateDialect);
        properties.put("hibernate.show_sql", hibernateShowSql);
        properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);

        return properties;
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

The above posted code still needs a appliction.properties file right.
How do I add this <mapping class="com.lynas.test.Student" />
But which is the best practice?..
@AshishAugustine it depends on the project you are working on. Java configuration is more modern way.
1

A more modern, working solution:


@Configuration
@ComponentScan(basePackageClasses = {массив пакетов с классами @Component, @Service, @Repository, @Controller})
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.jdev.blog.admin.crud.repositories", entityManagerFactoryRef = "entityManagerFactory")
public class ApplicationConfiguration { 
   @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);

        entityManagerFactoryBean.setJpaProperties(hibProperties());

        return entityManagerFactoryBean;
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
}

Comments

0

NO the above database configration cannot be moved to a java file BUT can be moved to dispactcher servelet.Actually that whole hibernate.cfg.xml is not required from spring 2.5 version upwards. You can do the set up of the hibernate properties inside the dispatcher servlet like this. The below code uses mysql dialect so replace it with your requirement also replace name of the database,username and password of the database.

 <?xml version="1.0" encoding="UTF-8" ?> 
 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
  <context:component-scan base-package="com.c.controllers" /> 
  <context:component-scan base-package="com.c.service" /> 
  <context:component-scan base-package="com.c.dao" /> 
  <mvc:annotation-driven /> 

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" /> 
  <property name="suffix" value=".jsp" /> 
  </bean>
 <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName">
  <value>com.mysql.jdbc.Driver</value> 
  </property>
 <property name="url">
  <value>jdbc:mysql://localhost:3306/"your database name"</value> 
  </property>
 <property name="username">
  <value>"insert username here"</value> 
  </property>
 <property name="password">
  <value>"insert password here"</value> 
  </property>
  </bean>
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <property name="dataSource">
  <ref bean="myDataSource" /> 
  </property>
 <property name="annotatedClasses">
 <list>
  <value>com.c.beans.Employee</value> 
  </list>
  </property>
 <property name="hibernateProperties">
 <props>
  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
  <prop key="hibernate.show_sql">true</prop> 
  <prop key="hibernate.format_sql">true</prop> 
  </props>
  </property>
  </bean>
 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" /> 
  </bean>
  <tx:annotation-driven transaction-manager="transactionManager" /> 
  </beans>

1 Comment

It IS possible to do so.. but the question is which is the best practice?..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.