2011-10-17 86 views
2

如果表沒有auto_increment,異常«org.hibernate.HibernateException:數據庫返回沒有本地生成的標識值»如果我嘗試在表中插入一些東西將被拋出。 Id映射如下:休眠:hbm2ddl.auto =更新和自動增量

@Id @GeneratedValue 
    private int id; 

我雖然有hbm2ddl.auto =更新。不幸的是,它不通過驗證在目標表上設置AUTO_INCREMENT。我可以實現它,沒有HQL,沒有原生SQL更好?

回答

2

hbm2ddl設置與標識GenerationType無關。

您可以編寫自己的ID /密鑰生成器類,並讓hibernate知道您自己的密鑰生成器類。然後,hibernate會從你自己的發生器獲得身份。

你可能想看看一些文章:

http://blog.anorakgirl.co.uk/?p=43

http://www.devx.com/Java/Article/30396/0/page/3

Hibernate ID Generator

用於生成ID的邏輯,這取決於你的需求。最簡單的方法是max(id)+1,你可以緩存性能的最大值(id)。那麼,如果在羣集環境中運行應用程序,則必須注意線程安全問題並緩存同步問題。

btw,你在玩哪個數據庫?

更新

開放http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-id,並搜索「5.1.2.2.1。各種附加發電機」看看,試試代型「增量」,如果你的應用程序沒有在集羣中運行。

+0

> btw,你在玩哪個數據庫? MySQL – AvrDragon

+0

但我真的不想從自定義生成器開始,我只是想讓Hibernate使所有ID列AUTO_INCREMENT,如果它們不是。有沒有簡單的方法來做到這一點? – AvrDragon

+0

檢查我的更新。 – Kent

1

在PostgreSQL我發現2路通過hbm2ddl.auto=create

1.

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
protected Integer id; 

的PostgreSQL使自動增量生成PK爲id serial not null即唯一的序列爲每個表

2.

@Id 
@Column(name = "id", unique = true, nullable = false, columnDefinition = "integer default nextval('hibernate_sequence')") 
@GeneratedValue(strategy = GenerationType.SEQUENCE) 
protected Integer id; 

在這種情況下,一些奇怪的東西與FK發生:

create table meals (
    id integer default nextval('hibernate_sequence') not null, 
    calories int4 not null, 
    date_time timestamp not null, 
    description varchar(255) not null, 
    user_id integer default nextval('hibernate_sequence') not null, 
    primary key (id) 
) 

在h2 autogenerate和autoincrement工作正常。