zoukankan      html  css  js  c++  java
  • Hibernate基础(2)

     一对多关系:

    一个Category对应多个Product,一个Product对应一个Category;

    1:为Category类增加Set<Product> products;

    2:为Category.hbm.xml增加one-to-many映射;

      <set name="products" lazy="false">
                  <key column="cid" not-null="false" />
                  <one-to-many class="Product" />
            </set>

        //一对多关系
        public static void oneToMany() {
            SessionFactory sf=new Configuration().configure().buildSessionFactory();
            Session s=sf.openSession();
            s.beginTransaction();
            //获得主键为28的Category对象
            Category c=(Category)s.get(Category.class, 28);
            //获得外键为28的Product集合
            Set<Product> set=c.getProducts();
            for(Product p:set) {
                System.out.println(p.getName());
            }
        }

    多对多关系:

    一个User可以购买多种Product,一种Product可以被多个User购买;所以User和Product之间可以是多对多关系 ;

    要实现多对多关系 ,要有一张 user_product中间表来维护它们之间的关系 ;

    参考:http://how2j.cn/k/hibernate/hibernate-many-to-many/42.html#nowhere

  • 相关阅读:
    文件路径与操作系统
    试验10
    shiyan9
    sql
    shiyan8
    iostream
    shiyan7
    CDMA
    试验6
    试验5
  • 原文地址:https://www.cnblogs.com/lastingjava/p/9912256.html
Copyright © 2011-2022 走看看