In addition to above said.
Via StandardServiceRegistry. To load a random properties in property format as resource:
String resourceName = "MyHibernate.properties";
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.loadProperties(resourceName).build();
sessionFactory = new MetadataSources(registry)
.addAnnotatedClass(SomeClass.class)
.buildMetadata()
.buildSessionFactory();
As xml resource:
String resourceName = "MyHibernate.cfg.xml";
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure(resourceName).build();
sessionFactory = new MetadataSources(registry)
.addAnnotatedClass(SomeClass.class)
.buildMetadata()
.buildSessionFactory();
Via Configuration. Load as random file path,
as property file path
String filePath = "filePath/MyHibernate.properties";
Properties properties = new Properties();
properties.load(new FileInputStream(filePath));
SessionFactory sessionFactory = new Configuration()
.addProperties(properties)
.addAnnotatedClass(SomeClass.class)
.buildSessionFactory();
as xml file path
String filePath = "filePath/MyHibernate.cfg.xml";
SessionFactory sessionFactory = new Configuration()
.configure(new File(filePath));
.addAnnotatedClass(SomeClass.class)
.buildSessionFactory();
Load as resource,
as xml resource
String resourceXmlName = "MyHibernate.cfg.xml";
SessionFactory sessionFactory = new Configuration()
.configure(resourceXmlName)
.addAnnotatedClass(SomeClass.class)
.buildSessionFactory();
To load properties as resource, load as standard path as described above, but transform resource name to file path like this:
String resourceName = "MyHibernate.properties";
URL fl = this.getClass().getClassLoader().getResource(resourceName);
//fl can be null, up to you how to handle this
System.out.println (fl.getPath()));