Spring + Hibernate应用程序的特定于环境的配置

时间:2015-06-26 21:01:01

标签: java xml spring hibernate maven

我正在努力使用不同的.properties文件为hibernate配置我的Spring应用程序。我的计划是创建一个maven属性,以反映我想要选择的环境,通过个人资料选择。然后在我的hibernate.cfg.xml上加载属性变量。

文件:hibernate.cfg.xml:

.... <property name="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</property>  ...

文件:persistence-dev.properties:

... hibernate.hbm2ddl.auto = create ...

文件:spring-context.xml:

... <context:property-placeholder location="classpath*:*persistence-${envTarget}.properties" /> ...

我在这里缺少什么?

4 个答案:

答案 0 :(得分:1)

hibernate.cfg.xml不受Spring管理。

尝试使用PropertyPlaceholderConfigurer(或者它的替代PropertySourcesPlaceholderConfigurer)来过滤它是没用的。

您可以使用Maven资源过滤支持:

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <hibernate.hbm2ddl.auto>dev</hibernate.hbm2ddl.auto>
        </properties>
    </profile>

    <profile>
        <id>prod</id>
        <properties>
            <hibernate.hbm2ddl.auto>validate</hibernate.hbm2ddl.auto>
        </properties>
    </profile>
</profiles>

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

您也可以将它与Spring配置文件支持一起使用(假设您愿意在构建期间将Spring配置文件名称传递给Maven,而不仅仅是使用运行时,如果您从Maven运行Spring配置文件相关测试,您将会执行此操作) :

    <profile>
        <activation>
            <property>
                <name>spring.profiles.active</name>
                <value>dev</value>
            </property>
        </activation>
        <properties>
            <hibernate.hbm2ddl.auto>dev</hibernate.hbm2ddl.auto>
        </properties>
   </profile>
   ...

答案 1 :(得分:0)

我是通过以下方式实现的:

将公共属性保存到hibernate.cfg.xml文件中的所有环境,如下所示。

 <hibernate-configuration>
        <session-factory>

            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>

            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>


            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>

            <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">update</property>

          <!-- DB mapping if any -->    
            <mapping class='classname'></mapping>


        </session-factory>
    </hibernate-configuration>

添加HibernateUtil.java类中的属性,这些属性在运行时根据环境(url,用户名,密码,方言)进行更改。您可以将这些属性值保存在不同的环境文件中,例如local.properties,dev.properties,并在运行时加载它们。

import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {

    static private org.apache.commons.configuration2.Configuration loadTestData;
    private static final SessionFactory sessionFactory;

    public HibernateUtil(){
         loadTestData = loadPropertiesFile("local");
    }

    static {
        try {

            Configuration cfg = new Configuration();
            cfg.setProperty("hibernate.connection.url", loadTestData.getString("connection.url"));
            cfg.setProperty("hibernate.connection.username", loadTestData.getString("connection.username"));
            cfg.setProperty("hibernate.connection.password", loadTestData.getString("connection.password"));
            cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            cfg.configure();

            sessionFactory = cfg.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("SessionFactory creation failed" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static org.apache.commons.configuration2.Configuration loadPropertiesFile(String filename) {
        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                        .configure(params.properties()
                                .setFileName(filename + ".properties"));
        try {
            org.apache.commons.configuration2.Configuration config = builder.getConfiguration();
            return config;
        } catch (ConfigurationException cex) {
            // loading of the configuration file failed
            System.out.println(filename + " is not loaded" + cex.getMessage());
            return null;
        }

    }
}

以下是local.properties文件,该文件位于资源文件夹

#hibernate properties
connection.url=jdbc:mysql://localhost:3306/rivigo
connection.username=root
connection.password=root

希望它有所帮助!

答案 2 :(得分:0)

要区分 Spring 配置文件,请使用 resources/logback-spring.xml 而不是 logabck.xml 并添加标签:

</configuration>
  <springProfile name="prod">
    ...
  </springProfile>
  <springProfile name="dev,qa,stg">
    <logger name="org.hibernate" level="DEBUG"/>
    <!-- Hibernate SQL statements-->
    <logger name="org.hibernate.type" level="ALL"/>
    <!-- SQL queries-->
    <logger name="org.hibernate.SQL" level="DEBUG" />
    <!-- SQL query parameters:-->
    <logger name="org.hibernate.type.descriptor.sql" level="TRACE" />
  </springProfile>
</configuration>

答案 3 :(得分:0)

如果您在启动时了解您的环境,您的资源目录中可以有多个 hibernate.cfg.xml 文件,如下所示:

resources/
 - hibernate.cfg.Development.xml
 - hibernate.cfg.Production.xml

然后在您的代码中,加载特定于环境的休眠文件:

Java

Environment environment = Environment.Development;
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure(String.format("hibernate.cfg.%s.xml", environment.toString())).build();
MetadataSources metadataSources = new MetadataSources(registry);
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

Scala

val environment: Environment = Environment.Development
val registry: StandardServiceRegistry = new StandardServiceRegistryBuilder().configure(s"hibernate.cfg.${environment.toString}.xml").build
val metadataSources: MetadataSources = new MetadataSources(registry)
val sessionFactory: SessionFactory = metadataSources.buildMetadata.buildSessionFactory

其中 Environment 是特定于语言的枚举类型。