问答详情
源自:1-11 通过Hibernate API编写访问数据库的代码

按照老师的方法做的,但是还是有问题

http://img2.mukewang.com/5a1192f700011c6313590693.jpg

代码:

import java.util.Date;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.hibernate.service.ServiceRegistry;

import org.hibernate.service.ServiceRegistryBuilder;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;


//测试类

public class StudentsTest {

private SessionFactory sessionFactory;

private Session session;

private Transaction transaction;

@Before

public void init()

{

//创建配置对象

Configuration config = new Configuration().configure();

//创建服务注册对象

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();

//创建回话工厂

sessionFactory = config.buildSessionFactory(serviceRegistry);

//会话对象

session = sessionFactory.openSession();

//开启事物

transaction = session.beginTransaction();

}

@After

public void destory()

{

transaction.commit();  //提交事物

session.close();  //关闭会话

sessionFactory.close();  //关闭会话工厂

}

@Test

public void testSaveStudents()

{

//生成一个学生对象

Students s = new Students(1,"张三丰","男",new Date(),"武当山");

session.save(s);  //保存对象进入数据库

}

}


提问者:美香 2017-11-19 22:20

个回答

  • 慕设计3439226
    2017-11-20 06:12:30
    已采纳

    可能是configure没有找到配置文件,试着在src文件下新建一个resource文件夹,把hibernate.cfg.xml文件放进去。然后更改代码为Configuration config = new Configuration().configure("/resource/hubernate.cfg.xml");