我无法弄清楚为什么对象不会通过Annotations进行映射。无论我尝试什么,我总是收到这个错误:
org.hibernate.MappingException: Unknown entity: com.hibernate.practice.Car
我松散地遵循教程here,但似乎无法正常工作。我试图将对象剥离到它的骨头(认为我在某处的代码中出错),但是再次,即使只有一个ID和一个名称Column,我仍然无法使其正常工作。
我的hibernate.cfg
来自Netbeans Hibernate教程。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/practicedb?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
另外,根据说明,我添加了HibernateUtil.java类。
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().addPackage("com.hibernate.practice").buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
我设置了一个简单的类。它是一个带有ID和名称的Car
。
@Entity
public class Car {
@Id
@GeneratedValue
@GenericGenerator(name="increment", strategy="incrememnt")
private long id;
@Column(name="car_name")
private String name;
public Car() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
最后,我正试图像这样测试这些东西:
@Test
public void testOutHibernate() {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Car car = new Car();
car.setName("red one");
session.save(car);
try {
Transaction t = session.beginTransaction();
session.save(car);
t.commit();
}
finally {
session.close();
}
session.close();
}
没有失败,我得到了Unknown Entity Exception
。有什么明显的东西让我失踪吗?
答案 0 :(得分:0)
您需要添加带注释的类,如下所示 -
sessionFactory = new AnnotationConfiguration()
.addAnnotatedClass(Car.class)
.addPackage("com.hibernate.practice")
.configure()
.buildSessionFactory();
您可以在此处找到有关addPackage()
方法的讨论 - https://forum.hibernate.org/viewtopic.php?f=1&t=980723。