0

What I really want to do is to enumerate all the persistence units (PUs) declared for an application. Since some answer in StackOverflow says such a service does not exist in JPA, the option seems to be parsing the persistence.xml file myself and get all the PUs declared there.

So, how to load the persistence.xml file?

AlexSC
  • 1,823
  • 3
  • 28
  • 54
  • Are you asking how to install an XML parser and use it to parse an XML file to retrieve specific data? If so, the question might be a bit too broad. – Aaron Sep 18 '18 at 16:08
  • Locate and open the file, probably with a ClassLoader, then put the InputStream into a XML parsing library. Then analyze the resulting tree. Do you have questions regarding a particular step? – Hero Wanders Sep 18 '18 at 16:08
  • @HeroWanders: Your tip on ClassLoader was what I wanted! I know how to parse a XML file. Thanks! – AlexSC Sep 18 '18 at 16:19
  • Cool, I have added an answer describing this in more detail. – Hero Wanders Sep 18 '18 at 21:00

1 Answers1

2

Loading the persistence.xml means obtaining an InputStream for it. Usually the file is located within the META-INF directory. To get it from there you can use a ClassLoader which in turn can be retrieved from your current class:

InputStream input = this.getClass().getClassLoader().getResourceAsStream("META-INF/persistence.xml");

After that you may pass it to one of the many XML parsing libraries (JAXP, JAXB, dom4j, ...) to read the desired information.

Hero Wanders
  • 3,237
  • 1
  • 10
  • 14