我试图为Hibernate测试运行简单的测试,但它失败了:
public class TestService {
static {
PropertyConfigurator.configure("log4j.properties");
}
public static void main(String[] args) {
String mail = "lelyak@gmail.com";
User user = new UserService().getByEmail(mail);
System.out.println("user info: " + user.toString());
System.out.println("\nTHE END");
}
}
这是输出:
02:24:53,166 ERROR main HibernateUtil:<clinit>:24 - org.hibernate.HibernateException: hibernate.cfg.xml not found
Exception in thread "main" java.lang.NullPointerException
at com.lelyak.controller.dao.ElementDAOImpl.getAllElements(ElementDAOImpl.java:76)
at com.lelyak.controller.service.UserService.getListOfObjects(UserService.java:39)
at com.lelyak.controller.service.UserService.getByEmail(UserService.java:52)
at com.lelyak.application.TestService.main(TestService.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
的HibernateUtil :
public class HibernateUtil {
private static Logger log = Logger.getLogger(HibernateUtil.class);
private static SessionFactory sessionFactory = null;
private static final Configuration configuration = new Configuration();
static {
try {
configuration.configure("hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory(new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry());
} catch (Exception e) {
log.error(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
cfg
文件位于项目文件夹中:
位于同一位置的
log4j.properties
是可读的。 cfg
文件出了什么问题?
有什么建议吗?
答案 0 :(得分:0)
Hibernate从类路径而不是文件系统中提取hibernate.cfg.xml
。因此,如果您将其放在src
或src\Java
中,具体取决于您的结构,则应该有效。
答案 1 :(得分:0)
您想要阅读文件夹WebContent
中的文件,您可以尝试使用喜欢此内容
InputStream st= getServletContext().getResourceAsStream("/hibernate.cfg.xml");
但我建议将hibernate.cfg.xml
放在src和你的代码
configuration.configure("hibernate.cfg.xml");
会好的。
答案 2 :(得分:0)
您需要将hibernate.cfg.xml放在src文件夹下,并在代码中执行此操作
configuration.configure();