我必须在Postgresql中的表中添加列 position 。我希望列自动增加。我创建序列并将列添加到表中:
CREATE SEQUENCE position_sequence START 1 MINVALUE 1 MAXVALUE 2147483647;
ALTER TABLE stage
ADD COLUMN position integer default nextval('position_sequence');
比起我在我的对象类中添加了适当的字段。 POJO看起来像这样:
@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;
它与 id 一起正常工作,但是当我创建新对象 Stg 时,会将空值放在位置中,而不是使用顺序。
控制台输出
Hibernate: insert into stg (name, position, id) values (?, ?, ?)