Hibernate 多对一连接表单向关联
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;
CREATE TABLE `join_table1` (
`person_id` int(11) NOT NULL,
`address_id` int(11) default NULL
) 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.Address" table="address2">
<id name="addressid" type="integer">
<generator class="increment"/>
</id>
<property name="addressdetail">
<column name="addressdetail"/>
</property>
</class>
<class name="example.singlentoone.Person" table="person2" 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>
<join table="join_table1"> //这个地方就是连接表的信息,而且一定要写到一的一边,不能写到n的一边哦
<key column="person_id"></key>
<many-to-one name="address" column="address_id"/>
</join>
</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 person2 (name, age, personid) values (?, ?, ?)
Hibernate: insert into join_table1 (address_id, person_id) values (?, ?)
Hibernate: insert into person2 (name, age, personid) values (?, ?, ?)
Hibernate: insert into join_table1 (address_id, person_id) values (?, ?)
Hibernate: insert into address2 (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