2012-07-23 76 views
1

可能重複的例子:
multiple database support for same JPA classs 需要支持MySQL和Oracle兩者

我有一個表

用戶(ID,姓名);

現在我想創建該表的JPA類,以便它可以支持這兩個數據庫。

該id應該是自動增量。

請通過提供一些示例來幫助我實現上述目標。

在此先感謝。

+1

*你*試過了什麼?你卡在哪裏?你遇到什麼問題? – 2012-07-23 11:55:19

+0

這可能是我個人不喜歡在Hibernate中使用註釋的原因之一......最後,當涉及到更改數據庫時,最終您會修改源代碼而不是配置文件。 – Less 2012-07-23 11:57:04

+0

你只需寫一個簡單的hbm文件和Pojo到你的table.just改變方言相對於你的數據庫它將適用於這兩個數據庫。 – NPKR 2012-07-23 11:58:11

回答

0

您應該選擇生成類型AUTO。我只用.hbm映射,但我的理解是有註釋它應該是這個樣子的是:

@Entity 
public class Employee { 
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private long id; 
1

發電機類型

增量

This generator supports in all the databases, database independent 
This generator is used for generating the id value for the new record by using the 

序列

Not has the support with MySql 
This generator class is database dependent it means, we cannot use this generator class for all the database, we should know whether the database supports sequence or not before we are working with it 

Reffer這個環節,它可能對你有所幫助。

http://www.java4s.com/hibernate/generators-in-hibernate/

1

就直接去GenerationType.TABLE,這是最輕便的。它不依賴於數據庫細節,因爲增量值是通過SQL完成的。另外我發現它比AUTO更合適,因爲相同的生成類型將獨立於數據庫提供者使用。您也可以在不使用TableGenerator的情況下使用它,但是因爲我們的目標是讓它的功能與所有數據庫完全相同,所以我們明確提供了所需的值。

你的情況映射是:

@Entity 
@TableGenerator(
    name="usersGenerator", 
    table="ID_GENERATOR", 
    pkColumnName="GENERATOR_KEY", 
    valueColumnName="GENERATOR_VALUE", 
    pkColumnValue="USERS_ID", 
    initialValue = 1, 
    allocationSize=1) 
public class Users { 
    @Id 
    @GeneratedValue(strategy= GenerationType.TABLE, 
        generator = "usersGenerator") 
    private Integer value; 

    private String name; 

    protected Integer getValue() { 
     return value; 
    } 

    protected void setValue(Integer value) { 
     this.value = value; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

同一個數據庫表(在這種情況下ID_GENERATOR)可以由多個臺發電機使用。如果需要,例如由於id的類型,同一個表可以存儲多個pk和值列。

TableGenerator的名稱對於持久性單元是全局的,因爲一般的生成器名稱都是。如果希望,註釋也可以定位到id屬性。

可能的警告:如果我沒有記錯,一些休眠版本組合不支持初始值。這通常不限制可移植性。只有當我們必須自動生成表格並重現完全相同的一組id值時,纔會出現問題。解決方法是在構建表後手動插入初始值。