I am writing unit tests for my company application with JUnit. My application uses hibernate via the JPA EntityManager interface. I’m trying to configure a hibernate session to inject while testing. The problem I’m having is that hibernate is apparently not scanning the correct package to pick up my entities.
I have a method to get a session like this (modified from this video):
public static EntityManager getEntityManager() {
if (sessionFactory == null) {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources(registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}
}
return sessionFactory.openSession();
}
Then I define the packagesToScan
property in my hibernate.cfg.xml file like this
<property name="packagesToScan">com.[my company].model</property>
When I call one of my business methods that executes an HQL query using class names of entities like this:
entityManager.createQuery("Select u from User u")
I get the error org.hibernate.hql.internal.ast.QuerySyntaxException: [my entity] is not mapped...
, which leads me to believe the entities are not being scanned. I think this is likely because they are in src/main/java/ while my hibernate session is being created and configured from src/test/java.
So the question is first, is my analysis correct and this is the problem? Second: how do I direct hibernate to scan my entities that are not in the same directory as the hibernate session?
I suspect this post may have my answer, but I don’t understand the answers there well enough to implement them correctly.