Hibernate - 使 id 值也能够直接在数据源中自动生成
Hibernate - make id value be able to be autogenerated directly in datasource as well
我正在使用 Hibernate ORM 框架制作 Spring 启动应用程序。
我的代码中有一个 @Entity
class:
@Entity
@Table(name = "thing")
public class Thing {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "thing_id")
private long id;
@Column(name = "name")
private String name;
@Column(name = "price")
private int price;
我可以成功地将 Thing
保存到我的数据源。 thing_id
按预期生成。
但我不能直接在数据库管理器(例如 DataGrip)中插入记录:
insert into thing (name, price)
values ('aaa', 123);
我在尝试插入时收到警告和相应的错误:
Following columns have no computed/default value and must be listed explicitly: thing_id
那么我怎样才能在数据库管理器中直接插入时自动生成列值呢?
如果您有一个想要自动递增的数字列,可以选择直接设置 columnDefinition。这样做的好处是,即使在没有休眠的情况下使用模式,它也会自动生成值。不过,这可能会使您的代码特定于数据库:
@Column(columnDefinition = "serial") // postgresql
@Column(columnDefinition = "integer auto_increment") // MySQL
我正在使用 Hibernate ORM 框架制作 Spring 启动应用程序。
我的代码中有一个 @Entity
class:
@Entity
@Table(name = "thing")
public class Thing {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "thing_id")
private long id;
@Column(name = "name")
private String name;
@Column(name = "price")
private int price;
我可以成功地将 Thing
保存到我的数据源。 thing_id
按预期生成。
但我不能直接在数据库管理器(例如 DataGrip)中插入记录:
insert into thing (name, price)
values ('aaa', 123);
我在尝试插入时收到警告和相应的错误:
Following columns have no computed/default value and must be listed explicitly: thing_id
那么我怎样才能在数据库管理器中直接插入时自动生成列值呢?
如果您有一个想要自动递增的数字列,可以选择直接设置 columnDefinition。这样做的好处是,即使在没有休眠的情况下使用模式,它也会自动生成值。不过,这可能会使您的代码特定于数据库:
@Column(columnDefinition = "serial") // postgresql
@Column(columnDefinition = "integer auto_increment") // MySQL