Hibernate总结之二实体与表的映射关系

来源:互联网 发布:软件项目外包网 编辑:程序博客网 时间:2024/05/17 02:31

       今天趁自己的心情不错,顺便来总结一下有关hibernate中实体与表的映射关系。写此文章有三个目的:第一,总结一下hibernate为以后查看方便。第二,通过此文章我相信能起到抛砖引玉的作用。第三,和爱好者一起切磋。

 

       hibernate中实体与表的映射关系我大概的分了十一种形式,基本映射、普通的集合映射、组件映射、复合主键映射、  继承映射(每棵继承树映射成一张表)、继承映射(每个子类映射成一张表)、继承映射(每个具体的类映射成一张表)、一对一的映射、一对多的映射、多对多的映射。

        

          首先介绍一下实体类的设计原则:

          

* 实现一个默认的(即无参数的)构造方法(constructor)。

* 提供一个标识属性(identifier property)(可选)。

* 使用非final的类 (可选)。

      * 为持久化字段声明访问器(accessors)。

 

     其次介绍一下每种映射:

 

   1.  hibernate基本映射

           hibernate基本映射指的是实体中普通属性(不包括集合和自定义类型)映射成表的属性。通过<property>标签将普通属性映射成表字段需要注意:如果实体类中的属性和sql中的关键字重复,必须采用column重新命名。

       如:<property name="name" column="u_name"/>

   2.  集合映射

        集合我们分为数据(array)、set、list、map,不同的集合类型与表通过不同的标签关联起来,它们分别对应的标签是<array/>、<set/>、<list/>、<map/>。

        如:

              <array name="arrayValue" table="array_table">

                      <key column="list_id"/>

                       <list_index column="list_index"/>

                       <element type="property type" column="list_value"/>

             </array>

            <set name="setValue" table="set_table">

                 <key column="set_id"/>

                 <element type="property type" column="set_value"/>

            </set>

             <list name="listValue" table="list_table">

                      <key column="list_id"/>

                       <list_index column="list_index"/>

                       <element type="property type" column="list_value"/>

             </list>

           <map name="mapValue" table="map_table">

                  <key column="map_id"/>

                  <map-key type="string" column="map_key"/>

                  <element type="element property" column="map_value"/>

            </map>

 3.component(组件)映射

          在hibernate中,component是某个实体的逻辑组成部分,它与实体最重要的区别是没有oid,component可以成为值对象。使用component的好处是:它实现了对象模型的细粒度的划分,对象层次更加分明,复用率更加高。

           如:

            <component name="contact">

                   <property name="email"/>

                    <property name="photele"/>

                    <property name="address"/>

              </component>

 

原创粉丝点击