标签:util 基础 one bsp png 数据库表 _id XML column
public class Student { private int id; private String name; private int age; private Grade grade; //get…set }
public class Grade { private int id; private String name; //get…set }
Grade.hbm.xml:
<hibernate-mapping package="cn.siggy.pojo"> <class name="Grade"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> </class> </hibernate-mapping>
Student.hbm.xml:
<hibernate-mapping package="cn.siggy.pojo"> <class name="Student"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <property name="age"/> <!-- 多对一 name 表示属性名 class 指明 属性对应的类 column指 数据库表中的列名 --> <many-to-one name="grade" class="Grade" column="grade_id" foreign-key="fk_grade" not-null="true"/> </class> </hibernate-mapping>
@Test public void testSave() throws HibernateException, SerialException, SQLException{ Session session = null; Transaction tx = null; try{ session = HibernateUtil.getSession(); tx = session.beginTransaction(); Grade grade = new Grade(); grade.setName("基础"); session.save(grade); Student stu = new Student(); stu.setName("张三疯"); stu.setAge(22); stu.setGrade(grade); session.save(stu); tx.commit(); }catch (HibernateException e) { if(tx!=null) tx.rollback(); e.printStackTrace(); throw e; }finally{ HibernateUtil.closeSession(); } }
控制台信息:
数据库表信息:
标签:util 基础 one bsp png 数据库表 _id XML column
原文地址:http://www.cnblogs.com/chxbar/p/6676471.html