Hibernate 多对一外键单向关联
一 模式介绍
多个人,对应一个地址,N to One
二 实体(省略getter和setter方法)
- public class Person
- {
- private int personid;
- private String name;
- private int age;
- private Address address;
- ......
- }
- public class Address
- {
- private int addressid;
- private String addressdetail;
- ......
- }
三 数据表结构
CREATE TABLE `address1` (
`addressid` int(11) NOT NULL,
`addressdetail` varchar(255) default NULL,
PRIMARY KEY (`addressid`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
CREATE TABLE `person1` (
`personid` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`address_id` int(11) default NULL,
PRIMARY KEY (`personid`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
四 映射方法
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="example.singlentoone.Person" table="person1" lazy="false">
<id name="personid" type="integer">
<generator class="increment"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="age" type="integer">
<column name="age"/>
</property>
<many-to-one name="address" column="address_id"/> //这里一定要注意,写在多的那端,不能写在一的那端
</class>
<class name="example.singlentoone.Address" table="address1">
<id name="addressid" type="integer">
<generator class="increment"/>
</id>
<property name="addressdetail">
<column name="addressdetail"/>
</property>
</class>
</hibernate-mapping>
五 测试类
- public static void main(String[] args)
- {
- Address a = new Address();
- a.setAddressdetail("北京市海淀区");
- Person yeeku1 = new Person();
- Person yeeku2 = new Person();
- yeeku1.setAge(22);
- yeeku1.setName("测试用户一 N to 1");
- yeeku2.setAge(22);
- yeeku2.setName("测试用户二 N to 1");
- yeeku1.setAddress(a);
- yeeku2.setAddress(a);
- Session session = HibernateSessionFactory.getSession();
- Transaction tx = session.beginTransaction();
- session.save(yeeku1);
- session.save(yeeku2);
- session.save(a);
- tx.commit();
- tx = null;
- HibernateSessionFactory.closeSession();
- }
六 测试结果
Hibernate: insert into person1 (name, age, address_id, personid) values (?, ?, ?, ?)
Hibernate: insert into person1 (name, age, address_id, personid) values (?, ?, ?, ?)
Hibernate: insert into address1 (addressdetail, addressid) values (?, ?)
如果
session.save(yeeku1);
session.save(yeeku2);
session.save(a);
以上三个的保存顺序没有关系,但是如果没有session.save(a);
就会报错:org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: example.singlentoone.Address