Hibernate(十)多表联查之双向多对多

双向之多对多

举例:师傅与徒弟
- 一个师傅可以教多个徒弟
- 一个徒弟可以拜多个师傅

代码实现:
1、工具类:HibernateUtil

public class HibernateUtilEX {
    private static Configuration configuration = null;
    private static SessionFactory sessionFactory = null;
    // 本地化线程、
    private static ThreadLocal<Session> localSession = null;

    static {
        try {
            // 加载Hibernate配置文件(默认加载bihernate.cfg.xml)
            configuration = new Configuration().configure();
            // 获取SessionFactory工厂对象
            sessionFactory = configuration.buildSessionFactory();

            localSession = new ThreadLocal<Session>();
        } catch (Exception e) {
            System.out.println("加载hibernate映射文件失败");
            e.printStackTrace();
        }
    }

    /**
     * 得到Session对象
     * 
     * @return Session
     */
    public static Session openSession() throws HibernateException {
        // 底层有一个Map<k,V>,K:线程ID,V:session ,一个线程绑定一个session
        Session session = localSession.get();
        if (session == null) {
            session = sessionFactory.openSession();
            localSession.set(session);
        }
        return session;
    }

    /**
     * 关闭Session
     * 
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = localSession.get();
        if (session != null) {
            session.close();
        }
        localSession.set(null);
    }
}

2、创建实体类
师傅实体类:MasterEntity

public class MasterEntity {
    private int id;
    private String skill;//技能
    private Set<ApprenticeEntity> apprentices;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getSkill() {
        return skill;
    }
    public void setSkill(String skill) {
        this.skill = skill;
    }
    public Set<ApprenticeEntity> getApprentices() {
        return apprentices;
    }
    public void setApprentices(Set<ApprenticeEntity> apprentices) {
        this.apprentices = apprentices;
    }
    @Override
    public String toString() {
        return "MasterEntity [id=" + id + ", skill=" + skill + ", apprentices=" + apprentices + "]";
    }
}

师傅配置文件:MasterEntity.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.zh.entity">
    <class name="MasterEntity" table="t_master">
        <!-- 映射标识属性(属性) -->
        <id name="id" column="id" type="int">
            <!-- 主键生成策略(自增主键) -->
            <generator class="native" />
        </id>

        <!-- 映射普通属性 -->
        <property name="skill" column="skill"></property>

        <!-- 关联映射(双向多对多) 注意:两端关联映射的table表名必须相同-->
        <set name="apprentices" table="master_apprentice">
        <!-- 第三张表对应的外键 -->
            <key column="master_id"></key>
            <!-- 关联对应的类和主键标识 -->
            <many-to-many class="ApprenticeEntity" column="apprentice_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

徒弟实体类:ApprenticeEntity

public class ApprenticeEntity {

    private int id;
    private String name;
    private Set<MasterEntity> master;   //师傅集合引用
    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<MasterEntity> getMaster() {
        return master;
    }
    public void setMaster(Set<MasterEntity> master) {
        this.master = master;
    }
    @Override
    public String toString() {
        return "ApprenticeEntity [id=" + id + ", name=" + name + "]";
    }
}

徒弟配置文件:ApprenticeEntity.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.zh.entity">
    <class name="ApprenticeEntity" table="t_apprentice">
        <!-- 映射标识属性(属性) -->
        <id name="id" column="id" type="int">
            <!-- 主键生成策略(自增主键) -->
            <generator class="native" />
        </id>

        <!-- 映射普通属性 -->
        <property name="name" column="name"></property>

        <!-- 关联映射(双向多对多) 注意:两端关联映射的table表名必须相同-->
        <set name="master" table="master_apprentice">
        <!-- 第三张表对应的外键 -->
            <key column="apprentice_id"></key>
            <!-- 关联对应的类和主键标识 -->
            <many-to-many class="MasterEntity" column="master_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

3、在总配置文件hibernate.cfg.xml里添加配置映射文件

<!-- 双向多对多 -->
        <mapping resource="com/zh/entity/MasterEntity.hbm.xml" />
        <mapping resource="com/zh/entity/ApprenticeEntity.hbm.xml" />

4、创建测试类:HibernateTest

public class HibernateTest {
    public static void main(String[] args) {
        HibernateTest test = new HibernateTest();
        test.doubleManyToMany();
    }

    // 双向多对多
    public void doubleManyToMany() {
        // 开启会话
        Session session = HibernatUtil.getSession();
        // 打开事物
        Transaction transaction = session.beginTransaction();
        /**
         * 实例化师傅1
         */
        MasterEntity master1 = new MasterEntity();
        master1.setSkill("佛山无影脚"); // 设置技能
        session.persist(master1); // 保存数据
        /**
         * 实例化徒弟1
         */
        ApprenticeEntity apprentice1 = new ApprenticeEntity();
        apprentice1.setName("梁丹");
        Set<MasterEntity> masters = new HashSet<MasterEntity>();
        apprentice1.setMaster(masters); // 设置师傅属性
        apprentice1.getMaster().add(master1); // 添加师傅
        session.persist(apprentice1); // 保存数据
        /**
         * 实例化徒弟2
         */
        ApprenticeEntity apprentice2 = new ApprenticeEntity();
        apprentice2.setName("梁宽");
        Set<MasterEntity> masters2 = new HashSet<MasterEntity>();
        apprentice2.setMaster(masters2); // 设置师傅属性
        apprentice2.getMaster().add(master1); // 添加师傅
        session.persist(apprentice2); // 保存数据
        /**
         * 实例化师傅2
         */
        MasterEntity master2 = new MasterEntity();
        master2.setSkill("咏春");
        Set<ApprenticeEntity> apprentice3 = new HashSet<ApprenticeEntity>();
        master2.setApprentices(apprentice3); // 师傅关联徒弟
        master2.getApprentices().add(apprentice1); // 添加徒弟
        session.persist(master2); // 保存数据

        transaction.commit();
        HibernatUtil.closeSession(session);
    }
}

执行结果:
这里写图片描述

总结:双向多对多关系相比其他的关联关系,显得稍微复杂了一点点,这个复杂度主要体现在对这种关联关系的理解上。和其他关联关系不同的是这种关联多出来了一张中间表,里面存放着两个表之间的外键。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值