我正在尝试从Cameron McKenzie的书“Hibernate Made Easy”中学习Hibernate,并且已经完成了本书中的所有步骤,但仍然遇到了问题。我有User类的以下源代码:
package com.examscam.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
@Entity
public class User {
private Long id;
private String password;
@Id
@GeneratedValue
public Long getId() {
return id;
}
public String getPassword() {
return password;
}
public void setId(Long id) {
this.id = id;
}
public void setPassword(String password) {
this.password = password;
}
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
config.configure();
new SchemaExport(config).create(true, true);
}
}
我有以下hibernate.cfg.xml文件:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost/examscam</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
我有以下persistence.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="Welcome1">
<class>com.examscam.model.User</class>
</persistence-unit>
</persistence>
我正在使用MySQL,并且MySQL服务器实例肯定正在运行。
我没有遇到任何编译错误或导入问题。
我重读了书中的说明,我看不到任何可能无意中错过的内容,例如我有JDBC驱动程序和必要的jar。
当我尝试运行此类时,Eclipse只返回错误消息
0 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - schema export unsuccessful
java.lang.NullPointerException
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:144)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:166)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:133)
at com.examscam.model.User.main(User.java:35)
[有时,它返回1而不是0,但我看不到任何明显的模式。]
有人可以建议我可以做些什么来使这项工作?这是非常令人沮丧的,显然,如果我不能让它运行,我根本无法做任何事情。
谢谢, 康纳