如何在基于 JAVA 的 spring config 中配置 Hibernate Db 连接设置

Posted

技术标签:

【中文标题】如何在基于 JAVA 的 spring config 中配置 Hibernate Db 连接设置【英文标题】:How to configure Hibernate Db connection settings in JAVA based spring config 【发布时间】:2017-06-14 16:21:56 【问题描述】:

目前我正在将我的 bean 创建和配置设置从基于 XML 移动到基于 JAVA 的 spring 配置。我坚持移动数据库设置?如何在基于 JAVA 的配置文件中编写这些休眠数据库设置?

<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" />

我已添加交易详情。我得到了这个例外:

引起:java.lang.ClassNotFoundException: org.hibernate.context.spi.CurrentSessionContext

【问题讨论】:

【参考方案1】:

这里是配置。我还添加了您在最终解决方案中肯定需要的事务管理功能。

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;
    

【讨论】:

谢谢 :) 让我检查并返回 我收到 NoClassDefFound 异常。我已经用更多的细节和例外更新了这个问题。你能帮忙吗? 我使用的是hibernate 3。你能传递进口吗? 添加了导入【参考方案2】:

接受的答案不完整。这段代码帮助了我:


@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;
    

【讨论】:

【参考方案3】:
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;
    

【讨论】:

欢迎来到 ***。虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。

以上是关于如何在基于 JAVA 的 spring config 中配置 Hibernate Db 连接设置的主要内容,如果未能解决你的问题,请参考以下文章

spring-cloud-starter-consul-config 和 spring-cloud-consul-config 区别是什么?从网上没有搜到答案,待跟进。

如何在基于 JAVA 的 spring config 中配置 Hibernate Db 连接设置

Spring之基于Java配置

为什么春天引导应用程序类需要有@Configuration注释?

Spring Boot使用thymeleaf模板时报异常:template might not exist or might not be accessible by any of the confi

如何将基于 java 的注释 maven 项目转换为 Spring Boot?