我的测试程序如下: package hibernateTest; import org.hibernate.*; import org.hibernate.cfg.*; import java.io.File; public class PersonTest { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 Configuration cfg; SessionFactory sf; Session session; Transaction tx;
Person person = new Person(); person.setId(100); person.setName("Wu Jicheng"); person.setSex("m"); person.setAddress("18 Shuangqing Road, Beijing"); try {
File file = new File("D:\\workspace\\Hibernate_Proj\\hibernate.cfg.xml"); cfg = new Configuration().configure(file);
sf = cfg.buildSessionFactory();
session = sf.openSession();
tx = session.beginTransaction();
session.save(person);
tx.commit();
session.close();
System.out.println("Data have been saved into database!");
感觉下面这两名,是不是有点问题呀! File file = new File("D:\\workspace\\Hibernate_Proj\\hibernate.cfg.xml"); cfg = new Configuration().configure(file); 一般的情况下,只需要用cfg = new Configuration().configure();这种方法就可以把配置文件给加上! 你再看一下配置文件是否正确!
package hibernateTest;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.io.File;
public class PersonTest { /**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
Configuration cfg;
SessionFactory sf;
Session session;
Transaction tx;
Person person = new Person();
person.setId(100);
person.setName("Wu Jicheng");
person.setSex("m");
person.setAddress("18 Shuangqing Road, Beijing");
try {
File file = new File("D:\\workspace\\Hibernate_Proj\\hibernate.cfg.xml");
cfg = new Configuration().configure(file);
sf = cfg.buildSessionFactory();
session = sf.openSession();
tx = session.beginTransaction();
session.save(person);
tx.commit();
session.close();
System.out.println("Data have been saved into database!");
}catch(HibernateException e) {
e.printStackTrace();
}
} }
另外hibrenate.cfg.xml下在src下的话new Configuration().configure();就可以了
它的默认值就是hibrenate.cfg.xml,默认去寻找classpath下的这个配置文件
File file = new File("D:\\workspace\\Hibernate_Proj\\hibernate.cfg.xml");
cfg = new Configuration().configure(file);
一般的情况下,只需要用cfg = new Configuration().configure();这种方法就可以把配置文件给加上!
你再看一下配置文件是否正确!