<1>one-to-many/many-to-one
(1)表结构
/**客户表**/
create table CUSTOMERS(
ID int not null auto_increment,
Name varchar(15),
primary key(ID)
);
/**订单表**/
create table ORDERS(
ID bigint not null auto_increment,
ORDER_NUMBER varchar(15),
CUSTOMER_ID int not null,
primary key(ID),
foreign key (CUSTOMER_ID) references CUSTOMERS(ID)
);
(2)Customers.hbm.xml
<set name="Orders" inverse="true" lazy="false" cascade="all"> <key column="CUSTOMER_ID"/> <one-to-many class="Orders"/> </set>
说明:inverse="true",Customers端无须维护这个关联关系。也就是当Customers对象变化时,不用同步更新它的关联的Orders(Orders这端的inverse="false",表明由它来维护关系),这样避免双方重复更新同一关系。
(3)Orders.hbm.xml
<many-to-one name="Customer" column="CUSTOMER_ID" class="Customers" not-null="true" > </many-to-one>
<2>many-to-many
(1)表结构
create table AUTHORIZATION(
ID bigint(20) not null auto_increment,
AUTH int(11),
AUTHORIZE int(11),
PRIMARY KEY (ID)
);
create table USR(
ID bigint(20) not null auto_increment,
NAME varchar(16),
PRIMARY KEY (ID)
);
/**双向关联的中间连接表**/
create table USERAUTH(
ID bigint(20) not null auto_increment,
USER_ID bigint(20),
AUTH_ID bigint(20),
PRIMARY KEY (ID)
);
(2)Authorization.hbm.xml
<set name="users" table="userauth" inverse="false" cascade="all"> <key column="AUTH_ID"/> <many-to-many class="Usr" column="USER_ID"/> </set>
(3)Usr.hbm.xml
<set name="auths" table="userauth" cascade="all" inverse="true"><!--由Authorization一端来维护关系--> <key column="USER_ID"/> <many-to-many class="Authorization" column="AUTH_ID"/> </set>
说明:多对多关系,通过一个中间连接表,分离成了两个一对多关系。
测试: