4

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?

AvrDragon
  • 7,139
  • 4
  • 27
  • 42

2 Answers2

3

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.

Community
  • 1
  • 1
Kent
  • 189,393
  • 32
  • 233
  • 301
  • >btw, which database are you playing with? MySQL – AvrDragon Oct 17 '11 at 12:33
  • but i don't really want to start with custom generator, i just want to make Hibernate make all ID Columns AUTO_INCREMENT, if they are not. Is any easy way to do that? – AvrDragon Oct 17 '11 at 12:35
2

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.

Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197