package cn.bdqn.studentInfo.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.After; import org.junit.Before; import org.junit.Test; import cn.bdqn.studentInfo.entity.Student; import cn.bdqn.studentInfo.entity.Teacher; /** * 测试类 * @author Administrator * */ public class testStu { private Configuration conf=null; private SessionFactory sessionFac=null; private Session session=null; private Transaction tx=null; /** * 正向创建数据表 */ @Test public void createDB(){ Configuration conf=new Configuration() .configure(); SchemaExport export =new SchemaExport(conf); export.create(true, true); } /** * 测试 */ @Test public void testMethod(){ Session session=new Configuration().configure().buildSessionFactory().openSession(); Transaction tx=session.beginTransaction(); try{ //创建两个学生对象 Student student1=new Student(); student1.setName("张同学"); student1.setId(9); Student student2=new Student(); student2.setName("王同学"); student2.setId(10); //创建两个老师对象 Teacher teacher1=new Teacher(); teacher1.setId(9); teacher1.setName("武老师"); Teacher teacher2=new Teacher(); teacher2.setId(10); teacher2.setName("程老师"); /** * 关联双方的关系 */ //告诉张同学,武老师和程老师都带着你的课 student1.getTeachers().add(teacher1); student1.getTeachers().add(teacher2); //告诉王同学,武老师和程老师都带着你的课 student2.getTeachers().add(teacher1); student2.getTeachers().add(teacher2); //告诉武老师,你现在带着王、张同学的课 teacher1.getStudents().add(student1); teacher1.getStudents().add(student2); //告诉程老师,你现在带着王、张同学的课 teacher2.getStudents().add(student1); teacher2.getStudents().add(student2); //添加 session.save(student1); session.save(student2); /*session.save(teacher1); session.save(teacher2);*/ tx.commit(); }catch (Exception e) { tx.rollback();//添加失败时,进行回滚 e.printStackTrace(); } } /** * 关闭session */ @After public void closeSession(){ if(session!=null){ session.close(); } } }