【问题标题】:Reading persistence.xml from a POJO从 POJO 中读取 persistence.xml
【发布时间】:2011-04-08 01:38:40
【问题描述】:

我创建了一个 EJB3 项目和一个 JPA 项目。我正在尝试创建一个帮助程序类(它将在一个单独的项目/jar 中),它将从我的 JPA 项目的 META-INF 文件夹中的persistance.xml 文件中返回持久性单元名称。

如何将此文件作为输入流读取?一旦获得对该文件的引用,我就可以解析这些值,但是如何从另一个 jar 的类中读取 jar 的 META-INF 文件夹中的文件?

请提供您的建议。

【问题讨论】:

    标签: java jar inputstream


    【解决方案1】:

    使用持久性单元一段时间后我遇到了问题(“突然”)。

    这是有帮助的(b******-解决方案,但问题仅在 devMode 中出现并通过此解决):

        try {
            InputStream is = Thread.currentThread().getContextClassLoader(
                    ).getResource("META-INF/persistence.xml").openStream();
            FileOutputStream output= new FileOutputStream("c:/tmp/show.xml");
            IOUtils.copy(is, output);
            IOUtils.closeQuietly(output);
            PersistenceUnitInfoImpl impl= new PersistenceUnitInfoImpl();
            impl.setPersistenceXmlFileUrl(new URL("file://c:/tmp/show.xml"));
            JpaBasics basics= new JpaBasics("spektrum");
            basics.init(false);
            EntityManager em= basics.getEm();
            _log.debug("have we an em: " + em);
            new TestLoad().testLoadMagazines();
        } catch (Exception e) {
            _log.error("", e);
        }
    }
    

    【讨论】:

      【解决方案2】:

      这行得通...

      InputStream is = Thread.currentThread().getContextClassLoader().getResource("META-INF/persistence.xml").openStream();
      

      【讨论】:

      • 一旦你得到对xml文件的引用(例如,作为上述答案中的输入流),使用DOM或SAX解析器读取持久单元节点的名称属性。
      【解决方案3】:

      如果您的其他 jar 在类路径中,您应该能够使用以下方法加载此文件: getClass().getResourceAsStream("META-INF/persistence.xml");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-09
        • 2012-02-08
        • 2013-06-07
        • 1970-01-01
        • 2019-11-22
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        相关资源
        最近更新 更多