5

Currently I am moving my beans creation and config settings from XML based to JAVA based spring config. I am stuck with moving db settings? How can I write these hibernate db settings in JAVA based config file?

<bean
    class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <value>
            hibernate.connection.driver_class=com.mysql.jdbc.Driver
            hibernate.connection.url=jdbc:mysql://url
            hibernate.connection.username=username
            hibernate.connection.password=password
            hibernate.dialect=org.hibernate.dialect.HSQLDialect
            hibernate.show_sql=false
            </value>

    </property>
    <property name="packagesToScan" value="com.test" />

</bean>


<tx:annotation-driven />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven proxy-target-class="true" />

I have added Transaction details. I am getting this exception:

Caused by: java.lang.ClassNotFoundException: org.hibernate.context.spi.CurrentSessionContext

3 Answers 3

6

Here is the config. I have also added transaction management features which you will definately need in the final solution.

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DbConfig{

@Bean
public DataSource getDatasource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://url");
        dataSource.setUsername("username");
        dataSource.setPassword("password");

        return dataSource;
    }

@Bean
public SessionFactory getSessionFactory() throws IOException{

LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
 sessionFactoryBean.setPackagesToScan("com.test");

//getHibernateProperties method is a private method 

  sessionFactoryBean.setHibernateProperties(getHibernateProperties());
    sessionFactoryBean.setDataSource(getDatasource());
    sessionFactoryBean.afterPropertiesSet();

    return sessionFactoryBean.getObject();
}

@Bean
    public HibernateTransactionManager getTransactionManager() throws IOException{
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory());

        return transactionManager;
   }


private static Properties getHibernateProperties() {

        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        hibernateProperties.put("hibernate.show_sql", false);
        // other properties

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

4 Comments

Thanks :) Let me check and get back
I am getting NoClassDefFound exception. I have updated the question with few more details and exception. Can you please help?
I am using hibernate 3. Can you please pass on the imports?
added the imports
0

The accepted answer isn't full. This code helped me out:


@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
import com.sda.hibernate.associations.one_to_many_bi.Child;
import com.sda.hibernate.associations.one_to_many_bi.Parent;
import com.sda.hibernate.associations.one_to_many_uni.Daughter;
import com.sda.hibernate.associations.one_to_many_uni.Mother;
import com.sda.hibernate.associations.one_to_many_uni_join.Father;
import com.sda.hibernate.associations.one_to_many_uni_join.Son;
import com.sda.hibernate.types.Player;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;

import java.util.Properties;

public class HibernateUtil {

    // get a session factory
    public static SessionFactory getSessionFactory() {
        Configuration configuration = createConfig();

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();

        return configuration.buildSessionFactory(serviceRegistry);
    }

    private static Configuration createConfig() {
        Configuration configuration = new Configuration();

        Properties settings = new Properties();
        settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
        settings.put(Environment.URL, "jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC");
        settings.put(Environment.USER, "root");
        settings.put(Environment.PASS, "root");
        settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL8Dialect");
        settings.put(Environment.SHOW_SQL, "true");
        settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
        settings.put(Environment.HBM2DDL_AUTO, "create-drop");

        configuration.setProperties(settings);

        // add annotated classes
        configuration.addAnnotatedClass(Player.class);
        configuration.addAnnotatedClass(Mother.class);
        configuration.addAnnotatedClass(Daughter.class);
        configuration.addAnnotatedClass(Father.class);
        configuration.addAnnotatedClass(Son.class);
        configuration.addAnnotatedClass(Child.class);
        configuration.addAnnotatedClass(Parent.class);

        return configuration;
    }
}

1 Comment

Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.