1、 学生表student 和年级表 grade
2、类Student 和Grade类
Student:
1 public class Student { 2 private int id; 3 private String name; 4 private int age; 5 //get…set 6 }
Grade:
1 public class Grade { 2 private int id; 3 private String name; 4 private Set<Student> students = new HashSet<Student>(0); //get…set 5 }
3、 映射文件
Grade.hbm.xml
1 <hibernate-mapping package="cn.siggy.pojo"> 2 <class name="Grade"> 3 <id name="id"> 4 <generator class="native"></generator> 5 </id> 6 <property name="name"/> 7 <!-- set是 Grade中的集合属性 name属性名称 --> 8 <set name="students"> 9 <!-- key表示外键 column外键列名--> 10 <key column="grade_id" not-null="true"></key> 11 <!-- one-to-many 一对多 类Grade 中 students 所表示类型 --> 12 <one-to-many class="Student"/> 13 </set> 14 </class> 15 </hibernate-mapping>
Student.hbm.xml
1 <hibernate-mapping package="cn.siggy.pojo"> 2 <class name="Student"> 3 <id name="id"> 4 <generator class="native"></generator> 5 </id> 6 <property name="name"/> 7 <property name="age"/> 8 9 </class> 10 </hibernate-mapping>
4、 测试代码
1 @Test 2 public void testSave() throws HibernateException, SerialException, SQLException{ 3 Session session = null; 4 Transaction tx = null; 5 try{ 6 session = HibernateUtil.getSession(); 7 tx = session.beginTransaction(); 8 Grade grade = new Grade(); 9 grade.setName("基础"); 10 11 Student stu = new Student(); 12 stu.setName("张三疯"); 13 stu.setAge(22); 14 Student stu1 = new Student(); 15 stu1.setName("老王"); 16 stu1.setAge(23); 17 //关联 18 grade.getStudents().add(stu); 19 grade.getStudents().add(stu1); 20 //保存数据的顺序 是根据外键的配置来决定的 21 //如果外键不能为null,那么先保存一的一端 22 //如果外键可以为null,则可以随意保存 23 session.save(grade); 24 session.save(stu); 25 session.save(stu1); 26 27 tx.commit(); 28 29 }catch (HibernateException e) { 30 if(tx!=null) 31 tx.rollback(); 32 e.printStackTrace(); 33 throw e; 34 }finally{ 35 HibernateUtil.closeSession(); 36 } 37 } 38 @Test 39 public void testGet(){ 40 Session session = null; 41 Transaction tx = null; 42 try{ 43 session = HibernateUtil.getSession(); 44 tx = session.beginTransaction(); 45 //取数据 46 Grade grade = (Grade)session.get(Grade.class, 1); 47 System.out.println("gradeName="+grade.getName()); 48 System.out.println("grade所对应的多的一端的数据"); 49 Iterator<Student> iter = grade.getStudents().iterator(); 50 for(;iter.hasNext();){ 51 Student temp = iter.next(); 52 System.out.println("name="+temp.getName()+"\tage="+temp.getAge()); 53 } 54 tx.commit(); 55 }catch (HibernateException e) { 56 if(tx!=null) 57 tx.rollback(); 58 e.printStackTrace(); 59 throw e; 60 }finally{ 61 HibernateUtil.closeSession(); 62 } 63 }