【问题标题】:hibernate.cfg.xml alternative in java filejava文件中的hibernate.cfg.xml替代品
【发布时间】:2014-12-21 04:49:41
【问题描述】:

我正在使用 spring 框架,对于数据库,我使用 hibernate.cfg.xml 以下列方式

<?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>

现在有什么办法可以在java文件中编写这段代码。像豆子什么的??

【问题讨论】:

    标签: java xml spring hibernate


    【解决方案1】:

    答案是肯定的。来自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;
        }
    
    }
    

    【讨论】:

    • 上面贴出来的代码还是需要一个appliction.properties文件对的。
    • 如何添加这个
    【解决方案2】:

    NO 上述数据库配置不能移动到 java 文件,但可以移动到 dispactcher servelet。实际上从 spring 2.5 版本开始不需要整个 hibernate.cfg.xml。 您可以像这样在调度程序 servlet 中设置休眠属性。下面的代码使用 mysql 方言,所以用你的要求替换它,也替换数据库的名称,数据库的用户名和密码。

     <?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>
    

    【讨论】:

      【解决方案3】:

      更现代、更有效的解决方案:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-25
        • 2012-02-28
        • 1970-01-01
        相关资源
        最近更新 更多