1、 学生表student 和年级表grade
2、类Student 和Grade类
Student:
1 public class Student { 2 private int id; 3 private String name; 4 private int age; 5 private Grade grade; 6 //get…set 7 }
Grade:
1 public class Grade { 2 private int id; 3 private String name; 4 //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 </class> 8 </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 <!-- 多对一 name 表示属性名 class 指明 属性对应的类 9 column指 数据库表中的列名 --> 10 <many-to-one name="grade" class="Grade" 11 column="grade_id" foreign-key="fk_grade" not-null="true"/> 12 </class> 13 </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 session.save(grade); 11 Student stu = new Student(); 12 stu.setName("张三疯"); 13 stu.setAge(22); 14 stu.setGrade(grade); 15 session.save(stu); 16 17 tx.commit(); 18 19 }catch (HibernateException e) { 20 if(tx!=null) 21 tx.rollback(); 22 e.printStackTrace(); 23 throw e; 24 }finally{ 25 HibernateUtil.closeSession(); 26 } 27 }