hibernate开发中遇到多对多的问题,可以转换为两个一对多

例如,现在有商品表,订单表,两者是多对多的关系,

--订单表
create table ORDERS
(
ID            NUMBER(8) not null,
TOTAL         NUMBER(8,2) not null,
CREATED_DATE VARCHAR2(40) not null,
REALNAME      VARCHAR2(20),
TELPHONE      VARCHAR2(20),
MOBILE        NUMBER(20),
ADDRESS       VARCHAR2(200) not null,
POSTCODE      VARCHAR2(12),
STATE         NUMBER(1),
ACCOUNT_ID    VARCHAR2(40),
PAYMENT_ID    NUMBER(4),
DELIVERY_ID   NUMBER(4),
PAYMENT_STATE NUMBER(1),
MEMO          VARCHAR2(400)
)

--商品表

create table PRODUCT
(
ID           NUMBER(8) not null,
NAME         VARCHAR2(200) not null,
CREATED_DATE VARCHAR2(40),
DESCRIPTION VARCHAR2(4000),
IMAGEURL     VARCHAR2(200),
PRICE        NUMBER(6,2) not null,
STOCK        NUMBER(8),
STATE        NUMBER(1) not null,
CATEGORY_ID NUMBER(4) not null,
DISCOUNT     NUMBER(2)
)

--中间表

create table ORDERITEM
(
ORDER_ID     NUMBER(8),
PRODUCT_ID   NUMBER(8),
ORIGIN_PRICE NUMBER(6,2),
PRICE        NUMBER(6,2),
QUANTITY     NUMBER(6),
ID           VARCHAR2(40) not null
)

 

传统的多对多映射会在order.hbm.xml中这样设置:

     
       
       
          
       

       

但是,此时中间表orderitem中多了三个字段,此时就不能用上面这种方法了,

那么就可以转化成两个一对多(或者说两个多对一)

步骤:

1.生成orderitem的POJO类,并改造成如下内容:

public class Orderitem implements java.io.Serializable {

// Fields

private String id;
private Double originPrice;
private Double price;
private Long quantity;

private Order order;
private Product product;

// Constructors

/** default constructor */
public Orderitem() {
}

// Property accessors

public String getId() {
   return this.id;
}

public void setId(String id) {
   this.id = id;
}

public Double getOriginPrice() {
   return this.originPrice;
}

public void setOriginPrice(Double originPrice) {
   this.originPrice = originPrice;
}

public Double getPrice() {
   return this.price;
}

public void setPrice(Double price) {
   this.price = price;
}

public Long getQuantity() {
   return this.quantity;
}

public void setQuantity(Long quantity) {
   this.quantity = quantity;
}

public Order getOrder() {
   return order;
}

public void setOrder(Order order) {
   this.order = order;
}

public Product getProduct() {
   return product;
}

public void setProduct(Product product) {
   this.product = product;
}

}

2.配置映射文件


"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


   
       
           
           
       

       
           
       

       
           
       

       
           
       

       

               cascade="save-update" >
       
       

       
         
       

   

3.接下来就变成多对一事务操作了(当然,从另一个方向看,就是一对多了)。

转载于:https://www.cnblogs.com/fengjian/archive/2012/07/09/2582117.html

你可能感兴趣的:(java,开发工具)