<many-to-one name="c" column="classId" class="com.base.model.Class"></many-to-one> //多对一
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping package="com.base.model"> 7 8 <class name="Student" table="t_student"> <!-- 类名与对应的数据表名 --> 9 <id name="id" column="stuId"> <!-- 字段名,设置主键 --> 10 <generator class="native"/> 11 </id> 12 <property name="name"/> <!--普通字段 --> 13 14 <many-to-one name="c" column="classId" class="com.base.model.Class"></many-to-one> //多对一 15 </class> 16 17 </hibernate-mapping>
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping package="com.base.model"> 7 8 <class name="Class" table="t_class"> <!-- 类名与对应的数据表名 --> 9 <id name="id" column="classId"> <!-- 字段名,设置主键 --> 10 <generator class="native"/> 11 </id> 12 <property name="name" column="className"/> <!--普通字段 --> 13 </class> 14 15 </hibernate-mapping>
1 <mapping resource="com/base/model/Student.hbm.xml"/> <!-- xml版使用resource --> 2 <mapping resource="com/base/model/Class.hbm.xml"/> <!-- xml版使用resource -->
1 public class StudentCalssTest2Test { 2 SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //由于每个步骤都会用到所以移到外面来 3 Session session; 4 @Before 5 public void setUp() throws Exception { 6 session = sessionFactory.openSession(); //生成一个新的session 7 session.beginTransaction(); //开启事物 8 } 9 10 @After 11 public void tearDown() throws Exception { 12 session.getTransaction().commit(); //提交事务 13 session.close(); //关闭session 14 } 15 16 @Test 17 public void testTestAdd() { 18 //简单添加示例 19 Class c = new Class(); 20 c.setName("2013级"); 21 session.save(c); 22 23 Student s1 = new Student(); //创建一个学生 24 s1.setName("zhansan"); //设置名称 25 s1.setC(c); 26 session.save(s1); //保存学生 27 28 Student s2 = new Student(); //创建一个学生 29 s2.setName("李四"); //设置名称 30 s2.setC(c); 31 session.save(s2); //保存学生 32 }
}
原文:http://www.cnblogs.com/sidianshui/p/4114658.html