hibernate中的关系映射05自关联(树状关联)

一、模型设计

1、实体类
package com.**.hibernate.pojo.tree;
public class Category {

    private Integer id;
    private String name;

    //父类别
    private Category parentCategory;

    //当前类型在树中的级别
    private Integer level;

    //父类和子类的一对多关系
    private Set<Category> categories = new HashSet<Category>();

}

2、xml
<hibernate-mapping package="com.**.hibernate.pojo.tree">

    <class name="Category" table="t_category">
        <id name="id" column="id">
            <generator class="native"></generator>
        </id>
        <property name="name" column="name"></property>
        <property name="level" column="level"></property>

        <!--父记录-->
        <many-to-one name="parentCategory" class="Category" column="parent_id" />
        <!-- 子己录 -->
        <set name="categories" inverse="true" order-by="id" cascade="all">
            <key column="parent_id"></key>
            <one-to-many class="Category"/>
        </set>
    </class>
</hibernate-mapping>

在Config配置中注入映射文件
<mapping resource="com/**/hibernate/pojo/tree/Category.hbm.xml" />

二、测试


1、save
package com.**.hibernate;
public class TreeTest {

    @Test
    public void testSave() {

        //一级分类
        Category category1 = new Category();
        category1.setName("家用电器");
        category1.setLevel(1);

        Category category2 = new Category();
        category2.setName("运动户外");
        category2.setLevel(1);

        //二级分类
        Category category11 = new Category();
        category11.setName("生活家电");
        category11.setLevel(2);

        Category category12 = new Category();
        category12.setName("大家电");
        category12.setLevel(2);

        //为家用电器添加二级分类
        //级联
        category1.getCategories().add(category11);
        category1.getCategories().add(category12);
        //关系
        category11.setParentCategory(category1);
        category12.setParentCategory(category1);

        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        session.save(category1);
        session.save(category2);

        tx.commit();
        session.close();

    }
}



2、search
 @Test
    public void testSearch() {

        Session session = HibernateUtil.openSession();

        Category category = session.get(Category.class, 1);
        System.out.println(category);

        session.close();

    }

数据库中的结构:

具体应用可以参考某东或者某宝的菜单


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值