AvrDragon
AvrDragon

Reputation: 7499

Hibernate: hbm2ddl.auto=update und autoincrement

If Table has no auto_increment, exception «org.hibernate.HibernateException: The database returned no natively generated identity value» will be thrown if i try insert something in Table. Id is mapped just as:

    @Id @GeneratedValue
    private int id;

I although have hbm2ddl.auto=update. Unfortunately it does not set AUTO_INCREMENT on destination Table, by validation. Can i achive it, without HQL and better without native SQL?

Upvotes: 4

Views: 2471

Answers (2)

Grigory Kislin
Grigory Kislin

Reputation: 18030

In PostgreSQL I've found 2 way to make autoincrement by hbm2ddl.auto=create

1.

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

PostgreSQL generate PK as id serial not null ie unique sequence for every table

2.

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

In this case something strange happened with 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)
)

In h2 autogenerate and autoincrement works OK.

Upvotes: 2

Kent
Kent

Reputation: 195229

hbm2ddl setting has nothing to do with Identity GenerationType.

You can write your own ID/key generator class, and let hibernate know your own key-generator class. Then hibernate will get identity from your own generator.

some articles you may want to take a look:

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

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

Hibernate ID Generator

for the logic to generate an ID, it depends on your requirement. The easiest way would be max(id)+1, you could cache the max(id) for performance. well, you have to take care about thread safe issue and also cache synchronization problem if you run the application in a cluster env.

btw, which database are you playing with?

update

open http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-id, and search "5.1.2.2.1. Various additional generators" take a look and try the generation type 'increment' if your application is not running in a cluster.

Upvotes: 3

Related Questions