请教一简单hibernate例子出现“/
hibernate.cfg.xml not found”异常!
初学hibernate,遇到头疼的问题,希望能得到各位的解答!
首先我建立了一个Java project,并将hibernate所需要的jar包、mysql所需要的jar包导入。
所创建的User.java代码如下:
package cn.itcast.hibernate.domain;
import java.util.Date;
public class User {
private int id;
private String name;
private Date birthday;
public int getId() {
return id;
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
所创建的User.htm.xml代码如下:<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="it.cast.hibernate.domain">
<class name="User">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<property name="birthday" />
</class>
</hibernate-mapping>
所创建的hibernate.cfg.xml代码如下:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///test</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="cn/itcast/hibernate/domain/User.htm.xml"/>
</session-factory>
</hibernate-configuration>
测试代码Base.java如下:
package cn.itcast.hibernate;
import java.io.File;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import cn.itcast.hibernate.domain.User;
public class Base {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
User user=new User();
user.setBirthday(new Date());
user.setName("name");
s.save(user);
s.close();
System.out.println("end");
}
}
运行Base.java,出现异常:
Exception in thread "main"
org.hibernate.HibernateException: /hibernate.cfg.xml not found
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 cn.itcast.hibernate.Base.main(Base.java:22)
在CSDN上找到类似的问题,但试过了所找到的方法,还是出现错误,希望能得到各位的指导!小弟先谢了!
------解决方案--------------------
hibernate.cfg.xml文件的默认位置是在源代码文件夹下。。。你看你这个位置有这个文件吗?