hibernate之多对多映射操作中间表

1.需求

1.1 在一个网上商城里有订单表,商品表,那么一个订单内可以有多个商品,一个商品可以被多个订单拥有。订单与商品就形成了多对多的关系,那么我们如何将这个关系通过hibernate映射到数据库呢?

1.2 解决思路,hibernate为我们提供了,多对多的映射,

    <set ...>
        <many-to-many>
    set>

这个方法的确可行,但是通过这个方法我们的中间表并不能操作其他数据,如订单记录中还有着数量以及购买单价字段,那么我们无法操作这些字段。

1.3 通过将多对多,转换为两个一对多的映射完成需求,并为中间表建立对应的实体。

2.实现

2.1 商品实体类

package com.lab9.domain;

import java.util.HashSet;
import java.util.Set;

public class Product {
    Integer id;
    String name;
    double price;
    String description;
    Set orderitems = new HashSet();
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Set getOrderitems() {
        return orderitems;
    }
    public void setOrderitems(Set orderitems) {
        this.orderitems = orderitems;
    }


}

2.2 订单实体

package com.lab9.domain;

import java.util.HashSet;
import java.util.Set;

public class Order {
    private Integer id;
    double total;
    String realname;
    String phone;
    String address;
    String postcode;
    Set orderitems = new HashSet();
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public double getTotal() {
        return total;
    }
    public void setTotal(double total) {
        this.total = total;
    }
    public String getRealname() {
        return realname;
    }
    public void setRealname(String realname) {
        this.realname = realname;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPostcode() {
        return postcode;
    }
    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }
    public Set getOrderitems() {
        return orderitems;
    }
    public void setOrderitems(Set orderitems) {
        this.orderitems = orderitems;
    }   
}

2.3 中间表(记录订单,商品,购买数量,购买单价)

package com.lab9.domain;

public class OrderItem {

    Integer id;
    Order order;
    Product product;
    int quantity;
    double purchase;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    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;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    public double getPurchase() {
        return purchase;
    }
    public void setPurchase(double purchase) {
        this.purchase = purchase;
    }

}

2.4 映射文件



 

<hibernate-mapping package="com.lab9.domain">
    <class name="Product" table="product">
        <id name="id" column="id" type="integer">
            <generator class="native">generator>
        id>
        <property name="name" type="string" length="16" not-null="true" column="name">property>
        <property name="price" type="double" column="price">property>
        <property name="description" type="string" length="16" column="description">property>

        
        <set name="orderitems" table="orderitem"> 
            <key column="product_id">key>
            <one-to-many class="OrderItem"/>
        set>
    class>
hibernate-mapping>


<hibernate-mapping package="com.lab9.domain">
    <class name="Order" table="orders">
        <id name="id" column="id" type="integer">
            <generator class="native">generator>
        id>
        <property name="total" type="double" not-null="true" column="total">property>
        <property name="realname" type="string" length="8" column="realname">property>
        <property name="phone" type="string" length="16" column="phone">property>
        <property name="address" type="string" length="16" column="address">property>
        <property name="postcode" type="string" length="6" column="postcode">property>

        
        <set name="orderitems" table="orderitem"> 

            <key column="order_id">key>

            <one-to-many class="OrderItem"/>

        set>
    class>
hibernate-mapping>


<hibernate-mapping package="com.lab9.domain">
    <class name="OrderItem" table="orderitem">
        <id name="id" column="id" type="integer">
            <generator class="native">generator>
        id>
        <many-to-one name="order" class="Order" column="order_id">many-to-one>
        <many-to-one name="product" class="Product" column="product_id" fetch="join">many-to-one>

        <property name="quantity" type="integer" column="quantity"   not-null="true">property>
        <property name="purchase" type="double"  column="purchase" not-null="true">property>
    class>
hibernate-mapping>

2.5测试类

public class Client {
    private static SessionFactory sf;
    private static Session session;


    public static void main(String[] args) {

        StandardServiceRegistry registy = new StandardServiceRegistryBuilder().configure().build();
        sf = new MetadataSources(registy).buildMetadata().buildSessionFactory();
        session = sf.openSession();
        Transaction tx = session.beginTransaction();

        //订单一
        Order order = new Order();
        order.setTotal(1000);
        order.setAddress("华软");
        order.setRealname("李浩然");
        order.setPostcode("510990");
        order.setPhone("87818998");

        //订单二
        Order order2 = new Order();
        order2.setTotal(5000);
        order2.setAddress("中大");
        order2.setRealname("李明");
        order2.setPostcode("510000");
        order2.setPhone("38008781");


        //产品1
        Product pro = new Product();
        pro.setName("thinkpad电脑");
        pro.setDescription("thinkpad");
        pro.setPrice(6780);

        //产品2
        Product p2 = new Product();
        p2.setName("彩电");
        p2.setDescription("性价比高");
        p2.setPrice(200);

        //产品3
        Product p3 = new Product();
        p3.setName("tcl彩电");
        p3.setPrice(3600);
        p3.setDescription("tcl彩电");

        //订单记录
        OrderItem item1 = new OrderItem();
        OrderItem item2 = new OrderItem();
        OrderItem item3 = new OrderItem();
        OrderItem item4 = new OrderItem();

        //一个订单有多条商品记录
        item1.setOrder(order);
        item1.setProduct(pro);
        item1.setQuantity(100);
        item1.setPurchase(6000);

        item2.setOrder(order);
        item2.setProduct(p2);
        item2.setQuantity(200);
        item2.setPurchase(3000);
        order.getOrderitems().add(item1);
        order.getOrderitems().add(item2);

        //一个商品有多条商品记录
        item3.setOrder(order2);
        item3.setProduct(p3);
        item3.setQuantity(30);
        item3.setPurchase(3300);

        item4.setOrder(order2);
        item4.setProduct(pro);
        item4.setQuantity(60);
        item4.setPurchase(6200);
        order2.getOrderitems().add(item3);
        order2.getOrderitems().add(item4);




        try
        {
            //保存记录
            session.save(order);
            session.save(pro);
            session.save(p2);
            session.save(item1);
            session.save(item2);
            session.save(order2);
            session.save(p3);
            session.save(item3);
            session.save(item4);

            //查询
            Order myOrder = (Order)session.get(Order.class, 9);
            if(myOrder != null)
            {
                int costMoney = 0;
                for(OrderItem item:myOrder.getOrderitems())
                {
                    costMoney += (item.getQuantity()*item.getPurchase());
                }
                System.out.println("订单号:"+myOrder.getId());
                System.out.println("总花费:"+costMoney+"\n"+"购买了以下商品:");
                for(OrderItem item:myOrder.getOrderitems())
                {
                    System.out.println("商品名:"+item.getProduct().getName());
                }

            }

            tx.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }
        session.close();
    }
}

你可能感兴趣的:(hibernate)