0

I need to extract the configuration file from a folder external to the project(C:/Propertiesexample/hibernateexample.cfg.xml), but it doesn't work for me, this is what I currently have and it works perfect when the configuration file is in the src/main of the project, but it's not what I'm looking for

public SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        try {
            // Create registry
            registry = new StandardServiceRegistryBuilder().configure(configFileName) .build();

            // Create MetadataSources
            MetadataSources sources = new MetadataSources(registry);
            
            // Create Metadata
            Metadata metadata = sources.getMetadataBuilder().build();
            // Create SessionFactory
            sessionFactory = metadata.getSessionFactoryBuilder().build();
            sessionFactory.getStatistics().setStatisticsEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
            if (registry != null) {
                StandardServiceRegistryBuilder.destroy(registry);
            }
        }
    }
    return sessionFactory;
}

I implemented this, but it doesn't work:

String hibernatePropsFilePath = "C:/exampleFolder/example.cfg.xml";

File hibernatePropsFile = new File(hibernatePropsFilePath);

Configuration configuration = new Configuration(); 
configuration.configure(hibernatePropsFile);

StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

StandardServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// Create registry

//Create MetadataSources
MetadataSources sources = new MetadataSources(serviceRegistry);

// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
sessionFactory.getStatistics().setStatisticsEnabled(true);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • See this https://stackoverflow.com/questions/20063330/how-to-load-hibernate-cfg-xml-from-different-location – Raja Ramachandran Jan 11 '23 at 06:36
  • Does this answer your question? [How to load hibernate.cfg.xml from different location](https://stackoverflow.com/questions/20063330/how-to-load-hibernate-cfg-xml-from-different-location) – Raja Ramachandran Jan 11 '23 at 06:38

0 Answers0