@Test public void testLoad() { Session session = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); Student stu1 = (Student) session.load(Student.class, 1); System.out.println(stu1.getName()); System.out.println(stu1.getClassroom().getName()); // 关联对象classroot也是延迟加载的 session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); if (null != session) { session.getTransaction().rollback(); } } finally { HibernateUtil.close(session); } }
@Test public void testAdd4() { Session session = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); Classroom c = new Classroom(); c.setGrade("2011"); c.setName("计算机"); // 此时classroom没有存,加了cascade="all" 会级联保存classroom Student stu1 = new Student(); stu1.setClassroom(c); stu1.setName("3243432"); session.save(stu1); Student stu2 = new Student(); stu2.setClassroom(c); stu2.setName("2234434432"); session.save(stu2); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); if (null != session) { session.getTransaction().rollback(); } } finally { HibernateUtil.close(session); } }