hibernate笔记汇总1

来源:互联网 发布:树莓派 tensorflow 编辑:程序博客网 时间:2024/06/09 23:39

转http://blog.csdn.net/fly_fish456/article/category/1190334

一、环境准备

  下载hibernate-distribution-3.3.2.GA-dist

   下载hibernate-annotations-3[1].4.0.GA

二、创建第一个Hibernate程序

    1)新建一个javaproject,导入hibernate需要的jar包:

                      i.     hibernate core

                   ii.     /required

               iii.     slf4j-nop jar(注意要和/required目录下的slf4j-api版本相对应 )

   2)引入MySql的JDBC驱动,在mysql中建立对应的数据库以及表

a)        create database hibernate;

b)        use hibernate;

create table Student (id int primary key,namevarchar(20), age int);

3)建立hibernate配置文件hibernate.cfg.xml

   在hibernate的文档中有对应的模版,将其复制下来,并修改成如下配置:

    <?xmlversion='1.0'encoding='utf-8'?>

<!DOCTYPEhibernate-configurationPUBLIC

       "-//Hibernate/Hibernate Configuration DTD3.0//EN"

       "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

 

<session-factory>

 

    <!-- Database connection settings -->

    <propertyname="connection.driver_class">

       com.mysql.jdbc.Driver

    </property>

    <propertyname="connection.url">

       jdbc:mysql://localhost/hibernate

    </property>

    <propertyname="connection.username">root</property>

    <propertyname="connection.password">123</property>

 

    <!-- JDBC connection pool (use thebuilt-in) -->

    <!-- <propertyname="connection.pool_size">1</property> -->

 

    <!-- SQL dialect -->

    <propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

 

    <!-- Enable Hibernate's automaticsession context management -->

    <!-- <propertyname="current_session_context_class">thread</property>-->

 

    <!-- Disable the second-level cache -->

    <propertyname="cache.provider_class">

       org.hibernate.cache.NoCacheProvider

    </property>

 

    <!-- Echo all executed SQL to stdout -->

    <propertyname="show_sql">true</property>

 

    <!-- Drop and re-create the databaseschema on startup -->

    <!-- <propertyname="hbm2ddl.auto">create</property> -->

    <!-- <propertyname="myeclipse.connection.profile"></property> -->

 

    <mappingresource="com/xuhaibin/hibernate/model/Student.hbm.xml"/>

   

</session-factory>

 

</hibernate-configuration>

 

<mapping> 要设置成对应的映射文件

4)建立Student的映射文件student.hbm.xml

参考文档中的示例映射文件,修改成如下内容:

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

       "-//Hibernate/Hibernate Mapping DTD3.0//EN"

       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 

<hibernate-mappingpackage="com.xuhaibin.hibernate.model">

    <classname="Student">

        <idname="id"/>

        <propertyname="name"/>

        <propertyname="age"/>

    </class>

</hibernate-mapping>

5)在com.xuhaibin.hibernate.model包下建立相应的Student类,生成get,set方法

6)建立测试类StudentTest内容如下:

[java] view plaincopy
  1.      import org.hibernate.Session;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4.   
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7.    
  8.   
  9.    
  10.   
  11. import com.xuhaibin.hibernate.model.Student;  
  12.   
  13.    
  14.   
  15.    
  16.   
  17. public class StudentTest {  
  18.   
  19.      public static voidmain(String[] args){  
  20.   
  21.          Student s = new Student();  
  22.   
  23.          s.setId(1);  
  24.   
  25.          s.setName("s1");  
  26.   
  27.          s.setAge(1);  
  28.   
  29.           
  30.   
  31.          Configuration cfg = newConfiguration();  
  32.   
  33.          SessionFactory sf =cfg.configure().buildSessionFactory();  
  34.   
  35.          Session session =sf.openSession();  
  36.   
  37.          session.beginTransaction();  
  38.   
  39.          session.save(s);  
  40.   
  41.          session.getTransaction().commit();  
  42.   
  43.          session.close();  
  44.   
  45.          sf.close();  
  46.   
  47.      }  
  48.   
  49. }  


三、使用annotation建立Teacher类,@Entity注解实体,@id注解主键

[java] view plaincopy
  1. package com.xuhaibin.hibernate.model;  
  2.   
  3.    
  4.   
  5. import javax.persistence.Entity;  
  6.   
  7. import javax.persistence.Id;  
  8.   
  9.    
  10.   
  11. @Entity  
  12.   
  13. public class Teacher {  
  14.   
  15.      private int id;  
  16.   
  17.      private String name;  
  18.   
  19.      private String title;  
  20.   
  21.       
  22.   
  23.      @Id  
  24.   
  25.      public int getId() {  
  26.   
  27.          return id;  
  28.   
  29.      }  
  30.   
  31.      public void setId(int id) {  
  32.   
  33.          this.id = id;  
  34.   
  35.      }  
  36.   
  37.      public String getName() {  
  38.   
  39.          return name;  
  40.   
  41.      }  
  42.   
  43.      public void setName(Stringname) {  
  44.   
  45.          this.name = name;  
  46.   
  47.      }  
  48.   
  49.      public String getTitle() {  
  50.   
  51.          return title;  
  52.   
  53.      }  
  54.   
  55.      public void setTitle(Stringtitle) {  
  56.   
  57.          this.title = title;  
  58.   
  59.      }  
  60. }  


在hibernate.hbm.xml中使用如下配置

<mapping class=”com.xuhaibin.hibern


***************************************************************************************************************************

一、为什么使用O/R Mapping

l        JDBC操作数据库很繁琐

l        Sql语句编写并不是面向对象的

l        可以在对象和关系表之间建立关联来简化编程

l        0/R Mapping 简化编程

l        0/R Mapping跨越数据库平台

l        参考Hibernate_0200_OR_Mapping_Simulation

 

二、Hibernate基础配置(参考Hibernate_0300_BasicConfiguration)

1)     先建表还是先建实体类

先建表,因为先建表可以在表上建立索引等,可以优化数据库。

2)     搭建日志环境并显示DDL语句

slf4j与log4j的关系:slf4j像是一个大管家,可以管理许多的日志框架,log4j是其中之一

加入slf4j-log4j.jar,加入log4j 的 jar 包,去掉 slf4-nop.jar

加入slf4j与log4j的对应jar包(slf4j-log4j12-1.5.8.jar)

从hibernate/project/etc 目录copy log4j.properties

査询hibernate文裆,日志部分,调整日志的输出策略

 

3)     show_sql 和format_sql

show_sql控制是否输出SQL语句

format_sql控制美化SQL语句<property name="format_sql">true</property>

         4) 表名和类名不同,对表名进行配置

               Annotation: @Table

 xml:hibernate文档  对象/关系映射... à 映射定义 à Doctype à class里面有对应的配置信息

       5) 字段名和属性相同

              不用写@column 与默认的@Basic效果一样

        Xml中不用写 column

6)     字段名和属性名不同

         Annotation: @Column

              xml:hibernate文档中查

   7) 不需要psersistence的字段(不用列)

        Annotation:@Transient              定义不写入数据库,属性透明

        xml不写

  8)映射日期与时间类型,指定时间精度

a)        Annotation:@Temporal(参数) 参数有3种 只显示时间,只显示日期,时间日期都显示

       //@Temporal(TemporalType.DATE) 只显示日期

       //@Temporal(TemporalType.TIME) 只显示时间

//@Temporal(TemporalType.TIMESTAMP) 显示日期与时间

b)        xml:指定type

       <class name="Teacher"table="Teacher" >

               <id name="id"column="id"></id>

               <propertyname="name" type="time"/>

        </class>

9)映射枚举类型( 比较少用)

a)        @Enumerated

       @Enumerated(EnumType.ORDINAL) 枚举类型按位置数,:0,1,2 ...存储

       @Enumerated(EnumType.STRING枚举类型按设定值存储

b)        xml:配置相当麻烦

10)字段映射的位置(field或者get方法)

best practice:保持 field(变量定义) 和 get set 方法的一致



***********************************************************************************

一、ID生成策略(参考hibernate_0400_ID)

1)xml生成id使用generator属性

         <idname="id" >

             <generatorclass="native"></generator>

         </id>

常用四个:native identitysequence uuid

2)注解方式:@GeneratedValue

a)           自定义ID

b)       AUTO(直接写@GeneratedValue 相当如native) (@GeneratedValue(strategy=GenerationType.AUTO))

                      i.     默认:对 MySQL,使用auto_increment

                   ii.     对 Oracle使用hibernate_sequence(名称固定)

c)       IDENTITY(@GeneratedValue(strategy=GenerationType.IDENTITY))

d)       SEQUENCE(@GeneratedValue(strategy=GenerationType.SEQUENCE))

                      i.     @SequenceGenerator(可自定义在数据库生成指定的sequence名)

          @Id

//@GeneratedValue中增加generator="teacherSEQ"

@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="teacherSEQ")

public int getId() {

                    returnid;

}

//"teacherSEQ"@SequenceGenerator的标识名

//"teacherSEQ_DB"为指定到数据库生成的Sequence

@Entity

@SequenceGenerator(name="teacherSEQ",sequenceName="teacherSEQ_DB")

e)       TABLE (可以忘记)

                        i.       @TableGenerator

@TableGenerator(

name="teacherID",                 //被调用的TABLE名字

            table="teacherID_DB",                //数据库建立的表名

            pkColumnName="key_value",

            pkColumnValue="pk_value",

            valueColumnName="teacher",             //pkColumnValue对应类名

            allocationSize=1                          //pkColumnValue对应类名

)

 

@GeneratedValue(strategy=GenerationType.TABLE,generator="teacherID ")

 

       注:如果使用注解方式的uuid如下:

              @Id

@GeneratedValue(generator="teacherUUID")

@GenericGenerator(name="teacherUUID",strategy="uuid")

 

二、联合主键

a)  Xml方式: composite-id

                     i.       将联合主键的属性提取出来,重新编写一个pojo类(原pojo类中的id,name要删除并新加入属性“StudentPK”)

       public class StudentPK implements Serializable {

                   privateString id;

                   privateString name;

                   … …

                 ii.       新建pojo类必须实现 java.io.Serializable序列化接

              iii.       新pojo类要重写equals和hashCode方法

@Override

public boolean equals(Object o) {

       if(oinstanceof StudentPk) {

              StudentPkpk = (StudentPk)o;

              if(this.id== pk.getId() && this.name.equals(pk.getName())) {

                return true;

              }

       }

       returnfalse;

}

 

@Override

public int hashCode() {

       returnthis.name.hashCode();

}

                 iv.       联合主键生成策略XML配置方法

       <hibernate-mapping>

                   <classname="com.bjsxt.pojo.Student" >

                            <composite-idname="studentPK" class="com.bjsxt.pojo.StudentPK">

                                     <key-propertyname="id"></key-property>

                                     <key-propertyname="name"></key-property>

                            </composite-id>

                            <propertyname="age" />

                            <propertyname="sex" />

                            <propertyname="good" type="yes_no"></property>

                   </class>

</hibernate-mapping>

 

b)  Annotation

                     i.       前三步与Xml方式前三步一样 都要建立新pojo类 都要实现Serializable接口 重写equals和hashCode方法.

                 ii.       方法1在新类前写@Embeddable,在原pojo类的新属性“TercherPK”的get方法前写@ld,如下

      @ Embeddable

public class TeacherPK implements Serializable {

                   privateString id;

                   privateString name;

                   … …

 

            @Entity

public classTeacher {

privateTeacherPK teacherPK ;

@Id

publicTeacherPK getTeacherPK() {

                            returnteacherPK;

}

… …

              iii.       方法2:@EmbeddedlD(*)  新pojo类无需加注解,只需在原pojo类新属性“TercherPK”的get方法前写@EmbeddedlD即可

                    iv.       方法3:@Id @IdClass(*)  新pojo类无需加注解,原pojo类的id,name属性保留不变,也无需新增“TercherPK”属性。 只在id,name的get方法前都加@Id,并在原pojo类前加@IdClass(TeacherPK).class),如下

@Entity

@IdClass(TeacherPK.class)

public class Teacher {

private String id;

private String name;

@Id

public String getId() {

              return id;

}

@Id

public String getName() {

              return name;

}


**************************************************************************************************



原创粉丝点击