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 (?, ?, ?)
3
  • @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 Commented Jan 24, 2019 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 Commented Jan 24, 2019 at 13:15
  • @caco3 I tried it but the result is the same Commented Jan 24, 2019 at 13:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.