2012-02-27 101 views
2

我正在创建一个简单的应用程序来学习Hibernate。我使用的是NetBeans IDE,我在com.hibernate包中创建了一个类。hibernate.cfg.xml未找到 - java中的异常

package com.mahesh.entity; 

import javax.persistence.Entity; 
import javax.persistence.Id; 

/** 
* 
* @author Mahesh 
*/ 
@Entity 
public class UserDetails { 
    @Id 
    private int userID; 
    private String userName; 

    public void setUserID(int userID) { 
     this.userID = userID; 
    } 

    public void setUserName(String userName) { 
     this.userName = userName; 
    } 

    public int getUserID() { 
     return userID; 
    } 

    public String getUserName() { 
     return userName; 
    } 
} 

我已经定义了一个hibernate.cfg.xml文件是在src文件夹(默认包)

:类被定义为:为

package com.hibernate; 

import com.mahesh.entity.UserDetails; 

import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.classic.Session; 

public class hibr { 
    public static void main(String[] args) { 
     UserDetails user = new UserDetails(); 
     user.setUserID(1); 
     user.setUserName("Mahesh"); 

     SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
     Session session = sessionFactory.openSession(); 
     session.beginTransaction(); 
     session.save(user); 
     session.getTransaction().commit(); 
    } 
} 

我已经定义的UserDetails类

这是由NetBeans IDE生成的错误。

2012年2月27日上午08时51分35秒org.hibernate.cfg.Configuration配置 信息:从资源配置:/hibernate.cfg.xml 2012年2月27日 上午08时51分35秒组织.hibernate.cfg.Configuration getConfigurationInputStream 信息:配置资源:/hibernate.cfg.xml线程中的异常 “main”org.hibernate.HibernateException:/hibernate.cfg.xml未找到 at org.hibernate.util.ConfigHelper .getResourceAsStream(ConfigHelper.java:147) at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405) at org.hibernate.cfg.Configuration.configure(Configuration.java:1427) at org.hibernate.cfg.Configuration.configure(Configuration.java:1414) at com.hibernate.hibr.main(hibr.java: 18)Java结果:1

回答

2

尝试

new Configuration().configure(<your cfg file path>).buildSessionFactory(); 
+0

请告诉我写的路径。我有我的cfg文件在NetBeans项目的src文件夹 – Max 2012-02-27 17:26:23

+0

如果你把它保存在src文件夹中,那么不需要给出路径,请确保该文件从src拷贝到netbeans的build文件夹中 – 2012-02-28 03:35:23

1

确保hibernate.cfg.xml文件也是在你的类路径,以便JVM可以看到它。

+0

如何在classpath中添加hibernate.cfg.xml文件我在NetBeans中工作。 – Max 2012-02-27 17:27:29

+0

我尝试在系统类路径中添加文件路径,但它的工作。请帮帮我 – Max 2012-02-27 17:33:04

1
new Configuration().configure() 

的配置()指的是类路径中构建文件夹。我曾经从src文件夹复制它来手动建立文件夹。清理完成后,生成文件夹将被删除。所以,我必须重复它。有没有什么办法可以使这个过程自动化?

我已经考虑

new Configuration().configure(new File("a path/hibernate.cfg.xml")) 

但在hibernate.cfg.xml的HBM文件的描述也涉及到资源的路径。 如何将这些文件与源目录自动完全一致地映射到构建目录中?