1. 在一对多的映射中,如果采用有序集合进行映射(在Hibernate中,有序列由hibernate来管理和维护),那么表结构为:
2. 类结构 Student.java
public class Student { private int id; private String name; private String sex; public Student() { } public Student(String name, String sex) { super(); this.name = name; this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Teacher.java
public class Teacher { private int id; private String name; private List<Student> students=new ArrayList<Student>(); public Teacher() { } public Teacher(String name) { super(); this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
3. 映射文件 Student.hbm.xml
<hibernate-mapping> <class name="cn.wh.vo.Student" table="t_student"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <property name="sex"/> </class> </hibernate-mapping>
Teacher.hbm.xml
<hibernate-mapping package="cn.wh.vo"> <class name="Teacher" table="t_teacher"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <!-- 一对多的关联映射 --> <list name="students"> <!-- key配置一的一端在多的一端的外键 --> <key column="tid"></key> <!-- 配置有序集合的有序列 默认从0开始 <index column="idx"></index>--> <!-- list-index可以指明 排序从哪里开始 --> <list-index base="1" column="idx"></list-index> <one-to-many class="Student"/> </list> </class> </hibernate-mapping>
4 . 测试
public class HibernateTest { private Session session=null; @Before public void setUp(){ session = HibernateUtil.getSession(); } @After public void tearDown(){ HibernateUtil.close(); } @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); //第一个参数 是否打印 数据库脚本 //第二个参数 是否将脚本导入数据库执行 export.create(true, true); } /** * 当关联映射是一对多时,保存数据时会多执行n条更新语句 */ @Test public void testInit(){ Transaction tx = null; try { tx = session.beginTransaction(); Teacher t1 = new Teacher("nico"); Teacher t2 = new Teacher("michile"); Student s1 = new Student("liming","男"); Student s2 = new Student("hanmei","女"); Student s3 = new Student("jim","男"); t1.getStudents().add(s1); t1.getStudents().add(s2); t2.getStudents().add(s3); session.save(t1); session.save(t2); session.save(s1); session.save(s2); session.save(s3); tx.commit(); } catch (Exception e) { if(tx!=null) tx.rollback(); } } @Test public void testGet(){ Teacher t = (Teacher) session.get(Teacher.class, 1); System.out.println("teacherName="+t.getName()); System.out.println("======================="); for(Student s:t.getStudents()){ System.out.println(s.getName()+"---"+s.getSex()); } } }