hibernate映射之单向多对一
数据模型:
person表
room表
实体对象模型:
Person private static final long serialVersionUID = 1L; private int pid; private String pname; private Room room;
Room private static final long serialVersionUID = 1L; private int rid; private String rname;
xml配置信息
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.skyedu.bean"> <class name="Person" table="person"> <id name="pid" column="pid" > <generator class="native"></generator> </id> <property name="pname" column="pname" length="32"></property> <many-to-one name="room" column="rid" class="Room" cascade="save-update"> </many-to-one> </class> </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.skyedu.bean"> <class name="Room" table="room"> <id name="rid" column="rid" > <generator class="native"></generator> </id> <property name="rname" column="rname" length="30"></property> </class> </hibernate-mapping>
测试代码:
@Test public void testSave(){ Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); try{ Room room = new Room(); room.setRname("水帘洞"); Person person1 = new Person(); person1.setPname("猴子1"); person1.setRoom(room); session.save(person1); transaction.commit(); }catch(Exception e){ transaction.rollback(); }finally{ HibernateUtil.closeSession(session); } } @Test public void testFind(){ Session session = HibernateUtil.getSession(); Person person = (Person) session.get(Person.class, 1); System.out.println("psersonName:"+person.getPname()); System.out.println("roomName:"+person.getRoom().getRname()); }