找不到hibernate.cfg.xml - java中的异常

时间:2012-02-27 03:53:34

标签: java hibernate

我正在创建一个简单的应用程序来学习Hibernate。我正在使用NetBeans IDE,并在 com.hibernate 包中创建了一个类。该类定义为:

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类定义为:

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;
    }
}

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

这是NetBeans IDE生成的错误。

  

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

确保hibernate.cfg.xml也在类路径中,以便JVM可以看到它。

答案 2 :(得分:1)

new Configuration().configure()

configure()指的是 build 文件夹中的类路径。我曾经手动将它从src文件夹复制到build文件夹。清理后,将删除构建文件夹。所以,我必须重复一遍。有没有办法自动化这个过程?

我考虑过了

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

但是hibernate.cfg.xml中的hbm文件描述也涉及资源路径。 如何自动将构建目录中的这些文件镜像为源目录?