Hibernate_開發基本步驟


一、准備Hibernate環境

  1. 導入Hibernate必須的jar包:導入hibernate-release-5.0.2.Final\lib\required下的jar包
  2. 加入數據庫驅動的jar

 

二、創建持久化Java

  1. 提供一個無參的構造器:使Hibernate可以使用Constructor.newInstance() 來實例化持久化類

      2.提供一個標識屬性(identifier property): 通常映射為數據庫表的主鍵字段. 如果沒有該屬性,一些功能將不起作用,如:Session.saveOrUpdate()

   3. 為類的持久化類字段聲明訪問方法(get/set): HibernateJavaBeans 風格的屬性實行持久化。

   4. 使用非 final : 在運行時生成代理是 Hibernate 的一個重要的功能. 如果持久化類沒有實現任何接口, Hibnernate 使用 CGLIB 生成代理. 如果使用的是 final , 則無法生成 CGLIB 代理.

   5. 重寫 eqauls hashCode 方法: 如果需要把持久化類的實例放到 Set (當需要進行關聯映射時), 則應該重寫這兩個方法

   6.Hibernate 不要求持久化類繼承任何父類或實現接口,這可以保證代碼不被污染。這就是Hibernate被稱為低侵入式設計的原因。

 

三、創建對象-關系映射文件

1. Hibernate 采用 XML 格式的文件來指定對象和關系數據之間的映射. 在運行時 Hibernate 將根據這個映射文件來生成各種 SQL 語句。

2. 映射文件的擴展名為 .hbm.xml

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-11-24 19:16:29 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="helloWorld.customer" table="CUSTOMER">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <!-- 指定主鍵的生成方式, native: 使用數據庫本地方式 -->
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="age" type="java.lang.String">
            <column name="AGE" />
        </property>
    </class>
</hibernate-mapping>

 

 

四、創建 Hibernate 配置文件

  1. Hibernate 從其配置文件中讀取和數據庫連接的有關信息, 這個文件應該位於應用的 classpath .
  2. 如何查找指定數據庫所使用的 SQL 方言:

    >  找到並且打開\hibernate-release-5.2.12.Final\project\etc目錄下的 hibernate.properties文件,在這里我選擇的是圖中的指定項

 

## MySQL

#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password


## Oracle

#hibernate.dialect org.hibernate.dialect.Oracle8iDialect
#hibernate.dialect org.hibernate.dialect.Oracle9iDialect
#hibernate.dialect org.hibernate.dialect.Oracle10gDialect
#hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
#hibernate.connection.username ora
#hibernate.connection.password ora
#hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl
#hibernate.connection.url jdbc:oracle:thin:@localhost:1522:XE

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    
        <!-- 配置連接數據庫的基本信息 -->
        <property name="connection.username">root</property>
        <property name="connection.password">ds756953242</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///hibernate</property>
        
        <!-- 配置 hibernate 的基本信息 -->
        <!-- hibernate 所使用的數據庫方言 
        <property name="dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>        
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>        
        
        <!-- 執行操作時是否在控制台打印 SQL -->
        <property name="show_sql">true</property>
    
        <!-- 是否對 SQL 進行格式化 -->
        <property name="format_sql">true</property>
    
        <!-- 指定自動生成數據表的策略 -->
        <property name="hbm2ddl.auto">update</property>
        
        <!-- 指定關聯的 .hbm.xml 文件 -->
        <mapping resource="helloWorld/customer.hbm.xml"/>
    
    </session-factory>
</hibernate-configuration>

 

五、通過 Hibernate API 編寫訪問數據庫的代碼

 

//1. 創建一個 SessionFactory 對象
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();  
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry)  
                .buildMetadata().buildSessionFactory();
      //2. 創建一個 Session 對象
        Session session = sessionFactory.openSession(); 
      //3. 開啟事務
        Transaction transaction = session.beginTransaction();  
        customer s = new customer("55", "小紅");  
      //4. 執行保存操作
        session.save(s);
      //5. 提交事務 
        transaction.commit(); 
      //6. 關閉 Session
        session.close();
      //7. 關閉 SessionFactory 對象
        sessionFactory.close();

 

 

六、此過程中出現的兩個錯誤

  1. org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table CUSTOMER (ID integer not null auto_increment, NAME varchar(255), AGE varchar(255), primary key (ID)) type=InnoDB]

  這個錯誤主要是所使用方言方面的錯誤,如果用的mysql版本是5.5版本以上的就需要把org.hibernate.dialect.MySQLInnoDBDialect改為org.hibernate.dialect.MySQL5InnoDBDialect才能用,或者直接使用org.hibernate.dialect.MySQLDialect,用了之后就可以成功建表了,如果沒改的話就需要手動建對應的表。

  2. org.hibernate.MappingException: Unknown entity: helloWorld.customer

  這個錯誤主要是創建SessionFactory時錯誤,如果用的Hibernate5.0版本以上的話就需要這樣創建按照 五 中的代碼那樣創建。

 

//        Configuration config = new Configuration().configure();  
//        //區別之處  
//        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()  
//                .applySettings(config.getProperties()).buildServiceRegistry();  
//          
//        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);  
//        Session session = sessionFactory.openSession();  
//        Transaction transaction = session.beginTransaction();  
//        Student s = new Student(1, "小明");  
//        session.save(s);  
//        transaction.commit();

 

  這個版本是之前Hibernate4.14的時候可以用的,到了Hibernate5之后就會出現代碼錯誤,因為4.1.2中的ServiceRegistryBuilder類在5.0.2中被刪除了,取而代之的是StandardServiceRegistryBuilder

 

//        Configuration config = new Configuration().configure();  
//        //區別之處  
//        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()  
//                .applySettings(config.getProperties()).build();  
//          
//        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);  
//        Session session = sessionFactory.openSession();  
//        Transaction transaction = session.beginTransaction();  
//        customer s = new customer("小明", "12");  
//        session.save(s);

 

  這個版本不會出現代碼錯誤,但是跑的時候就會出現org.hibernate.MappingException: Unknown entity: helloWorld.customer錯誤。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM