我正在尝试在运行简单 Java 应用程序并使用 Hibernate 的 Postgresql 数据库中创建两个带有几条记录的简单表。我已经创建了实体Employee
,并Department
如http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/中所述。我不使用 Maven。我的主要方法与两个实体位于同一个包中,如下所示:
@SuppressWarnings("deprecation")
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Department department = new Department();
department.setDepartmentName("Sales");
session.save(department);
Employee emp1 = new Employee("Nina", "Mayers", "111");
Employee emp2 = new Employee("Tony", "Almeida", "222");
emp1.setDepartment(department);
emp2.setDepartment(department);
session.save(emp1);
session.save(emp2);
session.getTransaction().commit();
session.close();
}
我的 hibernate.cfg.xml 文件是:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/testDB</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2dll.auto">create-drop</property>
</session-factory>
运行应用程序后,出现以下错误:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.al.hibernatetest.Department
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1063)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1433)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:205)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:190)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:91)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at com.al.hibernatetest.Main.main(Main.java:24)
由于我不知道的原因,休眠无法识别实体?可能是什么问题呢?配置中有什么?一个丢失的罐子?会话的创建中有什么?