代码部分:
import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; 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 StudensTest { private SessionFactory sessionFactory; private Session session; private org.hibernate.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); //保存对象进入数据库 } }
maybe丶xg
相关分类