依然是学生和学生卡的关联,这次是一对一单项主键关联
student.cfg.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.edu.hpu.model"> <class name="Student" table="student" dynamic-update="true"> <id name="id" column="id"> <!-- 靠外键的关联来设置主键 class="foreign" --> <generator class="foreign"> <param name="property">student</param> </generator> </id> <property name="name"></property> <property name="age"></property> </class> </hibernate-mapping>
(只改了这里)
StuIDCard.cfg.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="cn.edu.hpu.model.StuIDCard"> <id name="id"> <generator class="native"></generator> </id> <property name="num"/> <one-to-one name="student"></one-to-one> </class> </hibernate-mapping>生成的建表语句,StuIDCard里面也没有了student_id create table StuIDCard ( id integer not null auto_increment,num varchar(255),primary key (id) ) create table student ( id integer not null,name varchar(255) not null,age integer,primary key (id,name) ) schema export complete 但是你会发现没有建立外键联系,这个时候就很危险,会产生id不一致的情况! 如何在xml配置文件中进行外键联系: <one-to-one name="student" constrained="true"></one-to-one> constrained="true"意思就是帮你加一个外键关联约束。 新的建表语句: create table StuIDCard ( id integer not null auto_increment,name varchar(255),primary key (id) ) alter table StuIDCard add index FKD1E159DFFB389035 (id),add constraint FKD1E159DFFB389035 foreign key (id) references student (id) schema export complete 可以看到,已经加了外键关联(StuIDCard的ID字段上有小钥匙的图标)