Consider the hierarchy :
And the following classes and xml :
Define the Entity
class in Hibernate.cfg.xml
<mapping class="com.supernt.Department"/>
While creating the sessionFactory
object Load the Configuration file Like
SessionFactory factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
public static void main(String[] args) {
try{
// factory = new Configuration().configure().buildSessionFactory();
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}//you can write like this in your test class inside main method.this way you will be able to do the things using annotaions only
For those using Spring's Java configuration classes, you might write the following:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(Foo.class);
sessionBuilder.addAnnotatedClasses(Bar.class);
sessionBuilder.addAnnotatedClasses(Bat.class);
return sessionBuilder.buildSessionFactory();
}
Add the following to your xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>annotations</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
When I was trying to rewrite my example (from tutorialspoint) to use annotations, I got the same exception. This helped me (addAnnotatedClass()):
Configuration cfg=new Configuration();
cfg.addAnnotatedClass(com.tutorialspoint.hibernate.entity.Employee.class);
cfg.configure();
Use EntityScanner if you can bear external dependency.It will inject your all entity classes seamlessly even from multiple packages. Just add following line after configuration setup.
Configuration configuration = new Configuration().configure();
EntityScanner.scanPackages("com.fz.epms.db.model.entity").addTo(configuration);
// And following depencency if you are using Maven
<dependency>
<groupId>com.github.v-ladynev</groupId>
<artifactId>fluent-hibernate-core</artifactId>
<version>0.3.1</version>
</dependency>
This way you don't need to declare all entities in hibernate mapping file.