I was using hibernate 5.5
+ postgresql 13
I want to have auto generated sequence field (auto gen on database side instead of java side), which is equivalent to this DDL in postgres:
CREATE TABLE map_objects (
oid BIGSERIAL NOT NULL,
vid BIGSERIAL NOT NULL,
msg VARCHAR,
PRIMARY KEY (vid)
);
as you can see in the DDL, both vid
and oid
is auto gen in db side, however vid
is pk
but oid
is not
after I run this plain DDL sql in psql, I got 1 table and 2 sequences, the 2 sequences are used to generate default values for vid
and oid
Table "public.map_objects"
Column | Type | Collation | Nullable | Default
--------+-------------------+-----------+----------+------------------------------------------
oid | bigint | | not null | nextval('map_objects_oid_seq'::regclass)
vid | bigint | | not null | nextval('map_objects_vid_seq'::regclass)
msg | character varying | | |
I want to have a equivalent definition in hibernate entity declaration, here is what I've tried:
@Entity
public class MapObject {
@Id
@Generated(GenerationTime.INSERT)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long vid;
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Generated(GenerationTime.INSERT)
private Long oid;
private String msg;
}
the vid
is good, but the oid
is not working in the way I expected, it was inserting null
value for oid
, not even having an auto-gen value in java side.
try2: GenerateType.SEQUENCE
, but no luck.
try3:
@Column(name = "oid", columnDefinition = "BIGSERIAL", nullable = true)
private Long oid;
this approach basically manually define the column and the ORM know nothing about the entity, so after I insert the object, hibernate won't populate the generated oid
from db, it's still null in Java side, therefore this is still not my expected behavior....