2

I had to add column position to my table in postgresql. I wanted column to be auto-incremented. I create sequence and added column to the table:

CREATE SEQUENCE position_sequence START 1 MINVALUE 1 MAXVALUE 2147483647;
ALTER TABLE stage
ADD COLUMN position integer default nextval('position_sequence');

Than I added to my object class proper field. POJO looks like that:

@Entity
@Table(name = "stg")
public class Stg {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @NotNull
    @Size(max = 20)
    @Column(name = "name", length = 20, nullable = false)
    private String name;

    @Column(name = "from_date")
    private ZonedDateTime fromDate;

    @Column(name = "to_date")
    private ZonedDateTime toDate;

    @SequenceGenerator(name = "position_sequence", sequenceName = "position_sequence",allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="position_sequence") 
    private Integer position;

It works fine with id but when I create new object Stg it put null into position instead of use sequence.

Output from console:

Hibernate: insert into stg (name, position, id) values (?, ?, ?)
Tom
  • 303
  • 1
  • 4
  • 18
  • @SudhirOjha how can it help? I was reading this question and also tried to use *GenerationType.AUTO* instead of *GenerationType.SEQUENCE* but the clue is much different than there – Tom Jan 24 '19 at 12:46
  • You can use `@Column(insertable = false)`,on `position`. But I'm not sure if hibernate will pull the value set by database right after insert. See also [this question](https://stackoverflow.com/questions/14703697/how-can-i-use-db-side-default-value-while-use-hibernate-save) – Denis Zavedeev Jan 24 '19 at 13:15
  • @caco3 I tried it but the result is the same – Tom Jan 24 '19 at 13:19

0 Answers0