源自:1-11 通过Hibernate API编写访问数据库的代码
测试出现testSaveStudents[Runner:JUnit4],求解?代码如下。
package hibernate_test;
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 {
/**
* 执行顺序:
* 先before再test再after
*/
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-12 18:26