映射多对一和一对多双向关联
?? ? ? ?一个客户可能有多个订单,而客户对应数据库中的一个关系表,订单对应数据库中的一个关系表,表关系中客户表与订单表是一对多的关系,通常在多的一方通过一外键参考一的一方的主键。
1.数据库建表语句
customer的建表sql create table customer(
id int identity(1,1) not null,
name varchar(20)
)
order的建表sql create table order(
id int identity(1,1) not null,
ordernum varchar(20),
customerid int references customer(id) not null
)
2.对应的pojo对象
?
public class Customer{
?
private int id;
?
private String name;
private Set orders = new HashSet();
?
public int getId() {
return id;
}
?
public void setId(int id) {
this.id = id;
}
?
public String getName() {
return name;
}
?
public void setName(String name) {
this.name = name;
}
?
public Set getOrders() {
return orders;
}
?
public void setOrders(Set orders) {
this.orders = orders;
}
?
}
?
?
public class Order implements Serializable{
?
private int id;
private String orderNum;
private Customer customer;
?? ?public Order(){
?? ?
?? ?}
public Order(String orderNum,LoginUser user){
this.orderNum = orderNum;
this.user = user;
}
public int getId() {
return id;
}
?
public void setId(int id) {
this.id = id;
}
?
public String getOrderNum() {
return orderNum;
}
?
public void setOrderNum(String orderNum) {
this.orderNum = orderNum;
}
?
public Customer getCustomer() {
return customer;
}
?
public void setCustomer(Customer customer) {
this.customer= customer;
}
?
@Override
public boolean equals(Object obj) {
if(obj == this)
return true;
if(obj == null)
return false;
if(!(obj instanceof Order))
return false;
if(obj instanceof Order){
if(this.id != ((Order)obj).id)
return false;
if(this.orderNum != ((Order)obj).orderNum)
return false;
if(!this.user.equals(obj))
return false;
}
return this.equals(obj);
}
?
@Override
public int hashCode() {
return super.hashCode();
}
}
3.hibernate 配置文件order.hbm.xml<hibernate-mapping><class name="entity.Order" table="orders"><id name="id" column="id" type="int"><generator column="ordernum" type="java.lang.String"></property><many-to-one name="customer" not-null="true" cascade="save-update"><column name="customerid" not-null="true"/></many-to-one></class>?
?