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? 
            Asked
            
        
        
            Active
            
        
            Viewed 42 times
        
    1
            
            
         
    
    
        Ekaterina
        
- 1,642
- 3
- 19
- 36
- 
                    Is it java ee application? Do you use application server? – SternK May 21 '20 at 16:12
- 
                    No, it' Java SE application – Ekaterina May 21 '20 at 16:16
1 Answers
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