Hibernate Mapping Package

Can hibernate scan packages to create SessionFactory automatically?

No. You can't say Hibernate to scan packages for persistent classes even with the last Hibernate 5 version. Configuration has method addPackage(), but it is for reading "package-level metadata" (.package-info- files).

You don't want to use Spring, so what can you do:

Using fluent-hibernate

You can use
EntityScanner from fluent-hibernate library (you will not need to have other jars, except the library)

For Hibernate 4 and Hibernate 5:

Configuration configuration = new Configuration();
EntityScanner.scanPackages("my.com.entities", "my.com.other.entities")
.addTo(configuration);
SessionFactory sessionFactory = configuration.buildSessionFactory();

Using a new Hibernate 5 bootstrapping API:

List<Class<?>> classes = EntityScanner
.scanPackages("my.com.entities", "my.com.other.entities").result();

MetadataSources metadataSources = new MetadataSources();
for (Class<?> annotatedClass : classes) {
metadataSources.addAnnotatedClass(annotatedClass);
}

SessionFactory sessionFactory = metadataSources.buildMetadata()
.buildSessionFactory();

Using other libraries

If you already use a library that can be used for scanning, for an example Reflections, there is a test project with examples of using various libraries for entity scanning: hibernate-scanners-test.

Mapping all the classes in hibernate.cfg.xml with just one line?

You can't do it using Hibernate only.

You can use Spring with org.springframework.orm.hibernate5.LocalSessionFactoryBean (package hibernate5 for Hibernate 5, change it if need) or additional libraries as described here:

Hibernate config not list all Entities in XML

MappingException with hibernate.cfg.xml

Place Movie.hbm.xml under src/main/resources and change path in your config file as follows,

<mapping resource="Movie.hbm.xml" />

Hope this helps.

how to map classes in hibernate using the class attribute?

I should add this:

configuration.configure("hibernate.cfg.xml");
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());

to my HibernateUtil Class to tell that we want to configure using the hibernate.cfg.xml file and map the classes like this:

<mapping class="com.redpass.entities.Partie"/>
<mapping class="com.redpass.entities.Societe"/>


Related Topics



Leave a reply



Submit