【问题标题】:Hibernate add custom prefix to the catalogsHibernate 为目录添加自定义前缀
【发布时间】:2014-12-23 22:58:04
【问题描述】:

我使用的是 Hibernate 4.3.6,我需要根据环境为我的目录添加自定义前缀。我曾经在 4.2.3 版本中执行此代码

private static SessionFactory buildSessionFactory() {
    try {
        Configuration config = new Configuration();
        config.configure("db.cfg.xml");
        config.buildMappings();

        ServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(config.getProperties())
                .build();

        if (prefix != null && !prefix.isEmpty()) {
            Iterator<Table> iterator = config.getTableMappings();
            while (iterator.hasNext()) {
                Table table = (Table) iterator.next();
                table.setCatalog(prefix + table.getCatalog());
            }
        }
        //return new AnnotationConfiguration().buildSessionFactory(registry);
        SessionFactory factory = config.buildSessionFactory(registry);
        return factory;
    }
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println(ex);
        throw new ExceptionInInitializerError(ex);
    }
}

但现在出错了

config.buildSessionFactory(registry);

java.lang.ExceptionInInitializerError
at db.DatabaseEngine.buildSessionFactory(DatabaseEngine.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1456)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at db.DatabaseEngine.buildSessionFactory(DatabaseEngine.java:104)
... 26 more

除了目录,有没有像 ImprovementNamingStrategy 这样的东西?

【问题讨论】:

  • 您能否提供SSCCE 或提供所有来源(类和配置)? NullPointerException 出现在版本 4.3.6 配置类的奇怪位置。另外,您使用的是什么供应商和 Java 版本?
  • 如果我删除添加前缀的代码部分,它不会崩溃。 java vesion 是 1.7 和它的 sun。

标签: java database hibernate configuration schema


【解决方案1】:

根据Hibernate Annotation docs orm.xml XML 设置可以覆盖注解配置:

<entity-mappings 
  xmlns="http://java.sun.com/xml/ns/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
  version="2.0">

    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <schema>${db.schema}</schema>
            <catalog>${db.catalog}</catalog>
        </persistence-unit-defaults>
    </persistence-unit-metadata>

    <entity class="package.YourEntity1">        
        <table name="YOUR_TABLE_1" catalog="${specific_catalog1}"/>       
    </entity>

    <entity class="package.YourEntity2">        
        <table name="YOUR_TABLE_2" catalog="${specific_catalog2}"/>       
    </entity>

架构/目录变量可以由 Maven 根据您在构建之前运行的特定配置文件替换。这适用于默认目录和特定实体目录定义。

【讨论】:

  • 如果我在不同的 java 文件上有多个不同的目录怎么办?
  • 在这种情况下,您可以使用 Maven 在构建时过滤的 XML 实体声明覆盖 Java 注释表定义,就像我给您的示例一样。
  • 知道如何在服务启动时(使用 Tomcat 7 服务器)而不是在 Maven 构建时执行此操作。计划分发 JAR,而不是通过 Maven 在客户端计算机上构建。
  • 我认为 Hibernate 不支持运行时变量替换。您必须准备多个环境配置文件并在您的应用程序启动时提供正确的配置文件。这是一个运行时设计的东西。这不是微不足道但可行的。
  • Vlad 添加的文档已过期(Hibernate 3.5)。我可以找到解决此问题的最新文档是here(Hibernate 4.0)。要使用它,您需要使用 HibernateEntityManager,它是符合 JPA 规范的 SessionFactory 的包装器。有没有办法用 SessionFactory 做到这一点?
【解决方案2】:

创建 orm.xml 后,您可以使用以下代码加载它:

Configuration config = new Configuration();
config.configure("db.cfg.xml");
config.addResource("orm.xml"); // Load these files in any order
config.buildMappings();

有关如何创建 orm.xml 文件,请参阅 Vlad 的回答。

【讨论】:

    【解决方案3】:

    每个环境加载配置文件不会更简单,我的意思是(取决于环境)

    config.configure("db.cfg-env1.xml");
    

    config.configure("db.cfg-env2.xml");
    

    并在 jdbc 连接 url 中设置了正确的目录?

    接近实现的示例(感谢 serge 让我知道 :))

    config.configure(String.format("db.cfg-%s.xml"), env);
    

    【讨论】:

    • 那么第二个配置不会代替第一个而是累积?
    • 我的第一印象是,这会增加需要多个数据源和多个会话工厂,这可能会违反原始发布者的约束。
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2011-05-17
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2021-11-01
    相关资源
    最近更新 更多