IneQuation
IneQuation

Reputation: 1264

JUnit test, Hibernate and Unknown entity error

I'm trying to persist a very simple class using Hibernate. I'm not using Spring, I'm not using mapping files, just plain annotations. I am using javax.persistence.Entity instead of org.hibernate.Entity. Still, when running a JUnit test (located in a different package than the class, a test one), I'm getting testAddUser caused an ERROR: Unknown entity: restauracja.PersonalInfo.

What am I doing wrong?

UPDATE: This is how I initialize my session factory:

private final static SessionFactory factory;
static {
    Configuration cfg = new AnnotationConfiguration().configure("hibernate.cfg.xml");
    factory = cfg.buildSessionFactory();
}

And run the test:

@Test
public void testAddUser() {
    Session session = factory.openSession();
    Transaction tx = session.beginTransaction();

    PersonalInfo pi = new PersonalInfo("Jan", "Kowalski", "Krótka 6a", "Gniezno", 123456l);

    session.saveOrUpdate(pi);
    tx.commit();
    session.close();

}

Upvotes: 1

Views: 2191

Answers (1)

Gray
Gray

Reputation: 116828

Hibernate usually has a collection of classes that it knows about and has investigated for annotations. I suspect that you need to add your restauracja.PersonalInfo class to that collection. For example, in our test harness we do something like:

AnnotationConfiguration cfg = new AnnotationConfiguration();
for (Class<?> clazz : databaseConfig.getHibernateClasses()) {
    cfg.addAnnotatedClass(clazz);
}

Each of the classes that is used by the specific unit test needs to specify all of the classes that hibernate needs for the test must be in that list. I suspect that the list of classes is probably in the hibernate.cfg.xml file and you just need to add the missing class(es) to that list.

Upvotes: 4

Related Questions