Hibernate的主鍵產生器使用總結

來源:互聯網
上載者:User
 

Hibernate主鍵產生器的可選項說明:
1)
Assigned 

     主鍵由外部程式負責產生,無需Hibernate參與。
2) hilo 
     通過hi/lo
演算法實現的主鍵產生機制,需要額外的資料庫表儲存主鍵產生曆史狀態。
3) seqhilo 
     與hilo
類似,通過hi/lo
演算法實現的主鍵產生機制,只是主鍵曆史狀態儲存在Sequence中,適用於支援Sequence的資料庫,如Oracle。
4) increment 
     主鍵按數值順序遞增。此方式的實現機製為在當前應用執行個體中維持一個變數,以儲存著當前的最大值,之後每次需要產生主鍵的時候將此值加1作為主鍵。 
     這種方式可能產生的問題是:如果當前有多個執行個體訪問同一個資料庫,那麼由於各個執行個體各自維護主鍵狀態,不同執行個體可能產生同樣的主鍵,從而造成主鍵重複異常。因此,如果同一資料庫有多個執行個體訪問,此方式必須避免使用。
5) identity 
      採用資料庫提供的主鍵產生機制。如DB2、SQL
Server、MySQL中的主鍵產生機制。
6) sequence 
      採用資料庫提供的sequence
機制產生主鍵。如Oralce 中的Sequence。
7) native 
      由Hibernate根據底層資料庫自行判斷採用identity、hilo、sequence其中一種作為主鍵產生方式。 
8) uuid.hex 
      由Hibernate基於128
位唯一值產生演算法產生16 進位數值(編碼後以長度32
的字串表示)作為主鍵。
9) uuid.string 
      與uuid.hex
類似,只是產生的主鍵未進行編碼(長度16)。在某些資料庫中可能出現問題(如PostgreSQL)。
10) foreign 
      使用外部表格的欄位作為主鍵。

     一般而言,利用uuid.hex式產生主鍵將提供最好的效能和資料庫平台適應性。

     另外由於常用的資料庫,如Oracle、DB2、SQLServer、MySql
等,都提供了易用的主鍵產生機制(Auto-Increase
欄位或者Sequence)。我們可以在資料庫提供的主鍵產生機制上,採用generator-class=native的主鍵產生方式。不過值得注意的是,一些資料庫提供的主鍵產生機制在效率上未必最佳,大量並發insert資料時可能會引起表之間的互鎖。

     資料庫提供的主鍵產生機制,往往是通過在一個內部表中儲存當前主鍵狀態(如對於自增型主鍵而言,此內部表中就維護著當前的最大值和遞增量),之後每次插入資料會讀取這個最大值,然後加上遞增量作為新記錄的主鍵,之後再把這個新的最大值更新回內部表中,這樣,一次Insert操作可能導致資料庫內部多次表讀寫操作,同時伴隨的還有資料的加鎖解鎖操作,這對效能產生了較大影響。
      
     因此,對於並發Insert要求較高的系統,推薦採用uuid.hex
作為主鍵產生機制。

     如果需要採用定製的主鍵產生演算法,則在此處配置主鍵產生器,主鍵產生器必須實現
 net.sf.hibernate.id.IdentifierGenerator 
介面。

     例如:我們可以寫一個自己的主鍵產生類MyIdentifierGenerator 
並且實現public Serializable generate(SessionImplementor session,
Object object)
 throws
HibernateException;方法,代碼可能是這個樣子:

 

  1. public class MyIncrementGenerator implements IdentifierGenerator, Configurable {
  2.     
  3.     private static final Log log = LogFactory.getLog(MyIncrementGenerator.class);
  4.     
  5.     private long next;
  6.     private String sql;
  7.     
  8.     public synchronized Serializable generate(SessionImplementor session, Object object)
  9.         throws SQLException, HibernateException {
  10.         if (sql!=null) {
  11.             //獲得下一個主鍵的編號,可以自己定義
  12.             getNext( session.connection() );
  13.         }
  14.        return String.valueOf(next);
  15.     }
  16.     public void configure(Type type, Properties params, Dialect d)
  17.         throws MappingException {
  18.         
  19.         String table = params.getProperty("table");
  20.         if (table==null) table = params.getProperty(PersistentIdentifierGenerator.TABLE);
  21.         String column = params.getProperty("column");
  22.         if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK);
  23.         String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
  24.         returnClass = type.getReturnedClass();
  25.         
  26.         sql = "select max(to_number(" + column + ")) from " + ( schema==null ? table : schema + '.' + table );
  27.     }
  28.     private void getNext(Connection conn) throws SQLException {
  29.         PreparedStatement st = conn.prepareStatement(sql);
  30.         ResultSet rs = null;
  31.         try {
  32.             rs = st.executeQuery();
  33.             if ( rs.next() ) {
  34.                 next = rs.getLong(1) + 1;
  35.                 if ( rs.wasNull() ) next = 1;
  36.             }
  37.             else {
  38.                 next = 1;
  39.             }
  40.             sql=null;
  41.             log.debug("first free id: " + next);
  42.         }
  43.         finally {
  44.             if (rs!=null) rs.close();
  45.             st.close();
  46.         }
  47.     }
  48. }

然後再需要使用我們自訂的主鍵產生器構造主鍵的資料庫物件所對應的.XML檔案中可以這樣寫:

  1. <id name="uniqueid" column="UNIQUEID" type="string">
  2.      <generator class="com.core.persistence.MyIncrementGenerator"/>
  3. </id>


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.