在数据库设计中,很多实体之前并不是简单的一对一关系。有些可能是多对一,多对多关系。下面的文章中以常见的客户订单之间的关系为例,介绍在hibernate中,如果去配置多对一的关系。
1. 实体分析
客户和订单之间是一对多的关系,或者说订单和客户之间是多对一的关系。按照上面的思想,可以设计出两种方式的类关系。
//方式一
public class Customer{
private long id;
private String name;
private Set<Order> orders;
}
public class Order{
private long id;
}
//方式二
public class Customer{
private long id;
private String name;
}
public class Order{
private long id;
private Set<Customer>customers;
}
方式一方式二这样设计都是可以的,但是想想数据库sql语句怎么写呢?
create table order(
id int not null;
custom_id int not null;
primary key (id);
);
create table customer(
id int not null;
name varchar(30) ;
primary key (id);
);
可以看到方式二这种创建类的方法,更接近数据库表的结构。
2. hibernate的配置
//对于客户实体是很简单,类就只有id和name属性,表也只有id和name字段,直接
//简单的映射一下就行。
//而对于订单而言,类和数据库表中的id字段是可以做简单的对应的。但是customer_id
//这个字段就不好对应了。因为在类中是Customer对象,而在数据库表中是int型的外键
//对于上面的情况,使用many-to-one元素来做映射。
<many-to-one
name="customer" //类中的属性
column="customer_id" //表中的字段
class="mypack.Customer" //在Order类中,customer的类
not-null="true" //hibernate在存储订单的时候,会先检查customer属性是否为空
lazy="false"//表示hibernate在加载Order对象时,会立即加载与他想关联的Customer对象
/>