1

I'm trying to create a simple Hibernate (version 5.4) application with hibernate.cfg.xml file. I'm using SessionFactory. All the entities are annotated with @Entity. To my surprise, the application doesn't work without <mapping class="..."/> tags as well. No autodetaction works.
So I have to list entities twice - with the @Entity annotation in code and within the mapping tag in XML file. Is that correct?

Ekaterina
  • 1,642
  • 3
  • 19
  • 36

1 Answers1

1

You can initialize the hibernate's SessionFactory in the following way:

MetadataSources metadata = new MetadataSources(
   new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build()
);

for (Class<?> clazz: ClassUtil.getClassesForPackage("com.xxx.hibernate.entities"))
{
   if (clazz.isAnnotationPresent(Entity.class)) {
      metadata.addAnnotatedClass(clazz);
   }
}

Metadata meta = metadata.buildMetadata();
SessionFactory sessionFactory = meta.buildSessionFactory();

Where the ClassUtil.getClassesForPackage method uses one of approaches described in this question.

SternK
  • 11,649
  • 22
  • 32
  • 46