How to load hibernate.cfg.xml from different location

前端 未结 4 1227
说谎
说谎 2021-02-08 08:43

I am creating a jar using hibernate. I have encountered a situation where I need to change a setting (url) often, so I would like to load the hibernate.cfg.xml like

4条回答
  •  粉色の甜心
    2021-02-08 09:01

    Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error :

    Initial SessionFactory creation failed.org.hibernate.HibernateException: 
    /hibernate.cfg.xml not found
    

    To ask Hibernate look for your “hibernate.cfg.xml” file in other directory, you can modify the default Hibernate’s SessionFactory class by passing your “hibernate.cfg.xml” file path as an argument into the configure() method:

    SessionFactory sessionFactory = new Configuration()
                .configure("/com/example/persistence/hibernate.cfg.xml")
                .buildSessionFactory();
    
                return sessionFactory;
    

    Full Example in HibernateUtil.java, to load “hibernate.cfg.xml” from directory “/com/example/persistence/“.

    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
    
        private static final SessionFactory sessionFactory = buildSessionFactory();
    
        private static SessionFactory buildSessionFactory() {
            try {
                // load from different directory
                SessionFactory sessionFactory = new Configuration().configure(
                        "/com/example/persistence/hibernate.cfg.xml")
                        .buildSessionFactory();
    
                return sessionFactory;
    
            } catch (Throwable ex) {
                // Make sure you log the exception, as it might be swallowed
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    
        public static void shutdown() {
            // Close caches and connection pools
            getSessionFactory().close();
        }
    
    }
    

提交回复
热议问题