1、 实体类中使用List集合
1 public class Grade { 2 private int id; 3 private String name; 4 private List<Student> students = new ArrayList<Student>(0); 5 }
2、 映射文件
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 <list name="students" cascade="all"> 8 <!-- key表示外键 column外键列名--> 9 <key column="grade_id"></key> 10 <!-- 在多的一端 产生一列 用来表示顺序 如果不指明列名 默认为 idx 11 值由hibernate来维护 12 --> 13 <list-index column="sort"> 14 </list-index> 15 <!-- one-to-many 一对多 类Grade 中 students 所表示类型 --> 16 <one-to-many class="Student"/> 17 </list> 18 </class>
3、 测试代码
1 @Test 2 public void testSave() throws HibernateException, SerialException, SQLException{ 3 Configuration cfg = new Configuration().configure(); 4 SessionFactory factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder() 5 .applySettings(cfg.getProperties()).build()); 6 Session session = null; 7 Transaction tx = null; 8 try{ 9 session = factory.openSession(); 10 tx = session.beginTransaction(); 11 Grade grade = new Grade(); 12 grade.setName("基础"); 13 14 Student stu = new Student(); 15 stu.setName("张三疯"); 16 stu.setAge(22); 17 Student stu1 = new Student(); 18 stu1.setName("老王"); 19 stu1.setAge(23); 20 Student stu2 = new Student(); 21 stu2.setName("老李"); 22 stu2.setAge(23); 23 //关联 24 grade.getStudents().add(stu); 25 grade.getStudents().add(stu1); 26 grade.getStudents().add(stu2); 27 //保存数据的顺序 是根据外键的配置来决定的 28 //如果外键不能为null,那么先保存一的一端 29 //如果外键可以为null,则可以随意保存 30 session.save(grade); 31 session.save(stu); 32 session.save(stu1); 33 session.save(stu2); 34 35 tx.commit(); 36 37 }catch (HibernateException e) { 38 if(tx!=null) 39 tx.rollback(); 40 e.printStackTrace(); 41 throw e; 42 }finally{ 43 HibernateUtil.closeSession(); 44 } 45 } 46 @Test 47 public void testGet(){ 48 Session session = null; 49 Transaction tx = null; 50 try{ 51 session = HibernateUtil.getSession(); 52 tx = session.beginTransaction(); 53 //取数据 54 Grade grade = (Grade)session.get(Grade.class, 1); 55 System.out.println("gradeName="+grade.getName()); 56 System.out.println("grade所对应的多的一端的数据"); 57 List<Student> list = grade.getStudents(); 58 for(Student stu:list){ 59 System.out.println(stu.getName()); 60 } 61 tx.commit(); 62 }catch (HibernateException e) { 63 if(tx!=null) 64 tx.rollback(); 65 e.printStackTrace(); 66 throw e; 67 }finally{ 68 HibernateUtil.closeSession(); 69 } 70 }
时间: 2024-11-10 16:46:46