Hibernate充当应用程序和数据库之间的中间件,实现二者之间的交互操作,他对JDBC进行了封装,以完全面向对象的方式来操作数据。

适用于有多个数据源的情况下,不必去考虑不同数据源的操作差异。

     Hibernate将类型对象与数据库表建立映射关系,把类的属性映射称为数据库表的字段,Hibernate属性映射可分为简单属性映射、集合属性

映射、复合属性映射及派生属性映射。下面分别以实例介绍这几个映射及其对应的映射文件表示方式。

1、简单属性

     假设有个User类,对应数据库中的User表

     User类中的属性包括:                   <--------------->        user_info表中对应字段:

          id: int                                                                    id: primary key

          name: String                                                          name

          age:  int                                                                 age

          birthday: Date                                                         birthday

          salary:  float                                                            salary

    则可在*.hbm.xml中配置类对象到数据库表的映射关系如下(User.hbm.xml):

      

 1 <hibernate-mapping package="com.pattywgm.a_simple_test">
 2     <!--对象到表的映射 -->
 3     <class name="User" table="user_info">
 4         <!-- 
 5            id元素: 表示对象标识符OID即数据库表的主键
 6                          属性:type 元素类型
 7                column 数据库表中对应的列名
 8         -->
 9         <id name="id" type="int" column="id">
10             <!-- 
11                generator元素表示主键生成策略
12                native:根据底层数据库自动选择主键生成方式,identity,sequence,hilo
13              -->
14             <generator class="native"/>
15         </id>
16         <!--属性到列的映射 -->
17         <property name="age" type="int" column="age"></property>
18         <property name="name" type="string" column="name"/>    
19         <property name="birthday" type="date" column="birthday"/>    
20         <property name="salary" type="float" column="salary"/>    
21     </class>
22 
23 </hibernate-mapping>
View Code

相关文章: