Hibernate多对多关系映射拆解为两队多对一关系映射

例如商品表Items与类别表Category,在数据库里面新建两张表

步骤一:

create table Items(
id int auto_increment primary key,
name varchar(20) not null,
basePrice float not NULL
)

create table category (
cid int auto_increment primary key,
cname varchar(20) not null
)

insert into category values(null,'3c')
insert into category values(null,'2c')
insert into category values(null,'1c')
insert into category values(null,'wc')

insert into Items values(null,'手机','1200')
insert into Items values(null,'冰箱','2200')
insert into Items values(null,'电脑','4200')
insert into Items values(null,'微波炉','1200')

然后再在数据库里面新建中间表将二者关联起来

create table categoryItem(
id int auto_increment primary key,
category_id int not null,
items_id INT not null,
remark varchar(20) not null
)

insert into categoryItem values(null,1,2,'很好')
insert into categoryItem values(null,2,2,'一般')
insert into categoryItem values(null,3,4,'还不错')
insert into categoryItem values(null,4,3,'非常好')

步骤二:

然后再在myeclipse里面添加Items category 这两张表的持久化类ItemsCategory类

1)再在myeclipse里面新建一个categoryItem表对应的持久化类 CategoryItem

package hibernatedemo3;
public class CategoryItem {
    private int id;
    private Category category;
    private Items items;
    private String remark;
    public CategoryItem() {
        super();
        // TODO Auto-generated constructor stub
    }
    public CategoryItem(Category category, Items items, String remark) {
        super();
        this.category = category;
        this.items = items;
        this.remark = remark;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
    public Items getItems() {
        return items;
    }
    public void setItems(Items items) {
        this.items = items;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Override
    public String toString() {
        return "CategoryItem [id=" + id + ", category=" + category + ", items="
                + items + ", remark=" + remark + "]";
    }
}

2)再在上一步建好的Items、Category类里面添加Set集合属性,新建完成后的两个类分别为

package hibernatedemo3;

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

/**
 * Category entity. @author MyEclipse Persistence Tools
 */
public class Category implements java.io.Serializable {
    // Fields
    private Integer cid;
    private String cname;
    private Set<CategoryItem> categoryItem=new HashSet<CategoryItem> ();    
    // Constructors
    public Set<CategoryItem> getCategoryItem() {
        return categoryItem;
    }
    public void setCategoryItem(Set<CategoryItem> categoryItem) {
        this.categoryItem = categoryItem;
    }
    /** default constructor */
    public Category() {
    }
    /** full constructor */
    public Category(String cname) {
        this.cname = cname;
    }
    // Property accessors
    public Integer getCid() {
        return this.cid;
    }
    public void setCid(Integer cid) {
        this.cid = cid;
    }
    public String getCname() {
        return this.cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }
}

Items类

package hibernatedemo3;
import java.util.HashSet;
import java.util.Set;
/**
 * Items entity. @author MyEclipse Persistence Tools
 */
public class Items implements java.io.Serializable {
    // Fields
    private Integer id;
    private String name;
    private Float basePrice;
    private Set<CategoryItem> categoryItem=new HashSet<CategoryItem>();
    // Constructors
    public Set<CategoryItem> getCategoryItem() {
        return categoryItem;
    }
    public void setCategoryItem(Set<CategoryItem> categoryItem) {
        this.categoryItem = categoryItem;
    }
    /** default constructor */
    public Items() {
    }
    /** full constructor */
    public Items(String name, Float basePrice) {
        this.name = name;
        this.basePrice = basePrice;
    }
    // Property accessors
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Float getBasePrice() {
        return this.basePrice;
    }
    public void setBasePrice(Float basePrice) {
        this.basePrice = basePrice;
    }
    @Override
    public String toString() {
        return "Items [id=" + id + ", name=" + name + ", basePrice="
                + basePrice +  "]";
    }
}

3)配置三个持久化类所对应的映射文件Items.hbm.xml   Category.hbm.xml  CategoryItem.hbm.xml文件

Items.hbm.xml文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="hibernatedemo3.Items" table="items" catalog="wuliu">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20" not-null="true" />
        </property>
        <property name="basePrice" type="java.lang.Float">
            <column name="basePrice" precision="12" scale="0" not-null="true" />
        </property>
        <set name="categoryItem" inverse="false" cascade="save-update">
          <key column="items_id"></key><!-- column属性设定与所关联的持久化类对应的表的外键 -->
          <one-to-many class="hibernatedemo3.CategoryItem"/>
        </set>
    </class>
</hibernate-mapping>

Category.hbm.xml文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="hibernatedemo3.Category" table="category" catalog="wuliu">
        <id name="cid" type="java.lang.Integer">
            <column name="cid" />
            <generator class="native" />
        </id>
        <property name="cname" type="java.lang.String">
            <column name="cname" length="20" not-null="true" />
        </property>
        <set name="categoryItem" inverse="false" cascade="save-update">
         <key column="category_id"></key><!-- 中间连接表外键列 -->
         <one-to-many class="hibernatedemo3.CategoryItem"/>
        </set>
    </class>
</hibernate-mapping>

CategoryItem.hbm.xml文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="hibernatedemo3.CategoryItem" table="categoryItem" catalog="wuliu">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <!-- 非外键列映射 -->
        <property name="remark" type="java.lang.String">
            <column name="remark" length="20" not-null="true" />
        </property>
        <!-- column属性指定连接表外键列 -->
        <many-to-one name="items" column="items_id" class="hibernatedemo3.Items"></many-to-one>
        <many-to-one name="category" column="category_id" class="hibernatedemo3.Category"></many-to-one>
    </class>
</hibernate-mapping>
至此所有配置完毕

新建TestCategory测试类

package hibernatedemo3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestCategory {   
    private Configuration config;
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction tx;
    @Before
    public void init(){
        config=new Configuration().configure();
        sessionFactory=config.buildSessionFactory();
        session=sessionFactory.openSession();
        tx=session.beginTransaction();
    }
    @After
    public void destory(){
        tx.commit();
        session.close();
    }
    @Test //执行查找
    public void searchTest(){
        //查询商品
        Items items=(Items)session.get(Items.class,2);
        System.out.println(items);
    }
}
注意在各个持久化类里面避免打印时出现死循环打印,导致最后的栈内存溢出问题




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值