[Solved] Why the mapping.xml and configuration.xml has to be outside the pojo package?


I have just started to learn the Hibernate and found this in various online sites : mapping.xml and config.xml has to be defined outside the pojo package?

You can put xml configurations whenever you want. For an example

SessionFactory factory = new Configuration().configure().buildsessionFactory();

Configure a session factory from the default hibernate.cfg.xml. It is the same as

SessionFactory factory = new Configuration()
    .configure("hibernate.cfg.xml").buildsessionFactory();

So why hibernate.cfg.xml should be in the root of the source folder (or in the resources folder) in this situation?

Hibernate tries to load hibernate.cfg.xml via class loader

    InputStream stream = classLoader.getResourceAsStream( "hibernate.cfg.xml" );

if you specify just a name without a path ("hibernate.cfg.xml") a class loader will try to find a resource in the root of the compiled sources folder — bin or build folder, or the classes folder for war. The resources folder after build is copied (for an example, by Maven) in the root of the build or classes folder.

if you specify

new Configuration()
        .configure("/some/pojo/hibernate.cfg.xml").buildsessionFactory(); 

A class loader will try to find a resource in the some.pojo package. In this situation Hibernate removes the leading /, because of for a loading via a class loader the leading / is incorrect. So you can use a code below too

new Configuration()
        .configure("some/pojo/hibernate.cfg.xml").buildsessionFactory();

The same rule for other paths to the xml resources.

Also what’s the difference between JPA and Hibernate. I searched through web and According to me hibernate is just one of the implementation of JPA. Could u correct me.

Yes, Hibernate is an implementation of JPA. But one thing more. If you use the SessionFactory you can think that you don’t use JPA. But in the same time you use JPA annotations (@OneToMany for an example). When you use EntityManager — you use JPA exactly.

solved Why the mapping.xml and configuration.xml has to be outside the pojo package?