在处理来自互联网的代码时,我收到错误
Exception in thread "main" org.hibernate.MappingException: Unknown entity: Book
Book.java
public class Book {
private String isbn;
private String title;
private String author;
public Book() {
}
//getters and setters
保存数据:
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(
cfg.getProperties()).build());
Session session = sf.openSession();
session.beginTransaction();
Book book = new Book("12345767", "Welcome to hibernate","Test");
session.save(book);
session.getTransaction().commit();
System.out.println("data saved");
System.out.println("<------>");
session.close();
sf.close();
}
}
hibernate.cfg.xml中
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection Settings -->
<property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
Book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Book" table="books">
<id name="isbn">
<generator class="auto" />
</id>
<property name="title" />
<property name="author" />
</class>
</hibernate-mapping>
我无法解决此错误,因为我在映射文件中提供了所有内容。有什么方法可以解决这个问题吗?
答案 0 :(得分:1)
您的错误日志清楚地表明Hibernate无法为 jdbc:mysql
找到合适的驱动程序。
<强> 1。您是否在项目中添加了MySQL JDBC驱动程序库?
<强> 2。您尚未在以下行的hibernate.cfg.xml
文件中提供PORT编号: -
<property name="connection.url">jdbc:mysql://localhost/test</property>
用
替换此行<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
答案 1 :(得分:1)
按照rish的建议更改hibernate.cfg.xml
并在映射文件中使用类的完全限定名称,您可以尝试使用此代码创建SessionFactory:
Configuration configuration = new Configuration();
configuration.configure("/hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
答案 2 :(得分:0)