【发布时间】:2018-01-27 03:22:46
【问题描述】:
所以我有这个主要的
package Hibernate;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Hibernate {
/**
* @param args the command line arguments
*/
private static SessionFactory sessionFactory = null;
public static void main(String[] args) {
// TODO code application logic here
Session session = null;
try {
try {
sessionFactory = UtilHibernate.getSessionFactory();
session = sessionFactory.openSession();
List listapagos;
listapagos = session.createNativeQuery("SELECT * FROM pagos").list();
for (Object pagos : listapagos)
System.out.println(pagos.toString());
System.out.println("Finalizado.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
} finally {
session.close();
}
}
}
我只想从 MySQL 的数据库中将表加载到 List 中,然后显示它
还有 HibernateUtililty 类
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.*;
import org.hibernate.service.ServiceRegistry;
public class UtilHibernate {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new Configuration().configure().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;
}
}
一切都在同一个包中,包括 hibernate.reveng.xml、hibernate.cfg.xml 以及 tables.java 和 hbm.xml 文件。
这是我遇到的错误
INFO: HHH000206: hibernate.properties not found
Initial SessionFactory creation failed.org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.NullPointerException
at hibernate.Hibernate.main(Hibernate.java:42)
C:\Users\usuario\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
为什么会出现这个错误,我该如何解决?
【问题讨论】:
-
你需要把你的hibernate.cfg.xml放在类路径而不是包里面,或者你需要在configure方法中传递hibernate.cfg.xml的完整路径
标签: java hibernate netbeans-8