@GeneratedValue(strategy = GenerationType.AUTO) not working as thought

喜欢而已 提交于 2019-11-28 23:16:00

You may use GenerationType.TABLE. That way, jpa uses a sequence table for id assigment and you may never need to generate sequence or auto-increment values or triggers that lowers portability.

Also note that in java int type is initiated with 0 default, so you may get rid of that also.

In my case it was about bad dialect:

hibernate.dialect=org.hibernate.dialect.H2Dialect

instead of:

hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect

when I switched to the production database. Hibernate tried to use strategy prepared for different db engine.

Raedwald

I had a problem with a similar manifestation to yours. I eventually discovered that the configuration of my database connection was wrong: I was connecting to an old database that had an incorrect schema. The new schema declared the primary-key column as

"ID" BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)

so the database itself automatically generated the primary key whereas the old schema declared it as

"ID" INTEGER NOT NULL

Hibernate executed the correct code for the new schema, which failed on the old schema because the old schema demanded the SQL INSERT provide a value for the ID column.

Hibernate fails in silent and mysterious ways when the ID column is an Int. Try changing it to Long in the code and an unsigned 64-bit integer in the database. That fixed the issue for me.

Abdennour Toumi

Or try with @GeneratedValue(strategy = GenerationType.AUTO) instead of @GeneratedValue(strategy = GenerationType.SEQUENCE).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!