今天遇到一个问题,在运行项目的时候数据库中突然出现一个
hibernate_sequence
的表,这个表并不是我建的,于是把它删了。结果项目再运行就报错了,
could not read a hi value - you need to populate the table: hibernate_sequen..
could not read a hi value - you need to populate the table: hibernate_sequen..
解决办法:把数据库实体类的注解@GeneratedValue改成@GeneratedValue(strategy = GenerationType.IDENTITY)。
原因分析:@GeneratedValue默认的方式为hibernate_sequence,
Generated identifier values 的几种方式:
@GeneratedValue(strategy = GenerationType.IDENTITY)的意思是把Hibernate提供的主键生成策略设置为identity (即自增)
Using sequences
@Entity public class MyEntity { @Id @GeneratedValue(generation=SEQUENCE) public Integer id; ... }and it is the default style.@Entity public class MyEntity { @Id @GeneratedValue(generation=SEQUENCE, name="my_sequence") @SequenceGenerator( name = "my_sequence", schema = "globals", allocationSize = 30 ) public Integer id; ... }@Entity public class MyEntity { @Id @GeneratedValue(generation=SEQUENCE, name="my_sequence") public Integer id; ... }
Using IDENTITY columns
identity
a)根据底层数据库,来支持自动增长,不同的数据库用不同的主键增长方式。
b)特点: 与底层数据库有关,要求数据库支持Identity,如MySQl中是auto_increment, SQL Server 中是Identity。支持的数据库有MySql、SQL Server、DB2、Sybase和HypersonicSQL。
c)好处:在建表的时候指定了id为自动增长,实际开发中就不需要自己定义插入数据库的主键值,系统会自动顺序递增一个值 。Identity无需Hibernate和用户的干涉,使用较为方便,但由于依赖于数据库,所以不便于在不同的数据库之间移植程序。
Using identifier table
first . Table generator table structure
create table hibernate_sequences( sequence_name VARCHAR NOT NULL, next_val INTEGER NOT NULL )@Entity public class MyEntity { @Id @GeneratedValue(generation=TABLE) public Integer id; ... }Using UUID generation
@Entity public class MyEntity { @Id @GeneratedValue public UUID id; ... }@Entity public class MyEntity { @Id @GeneratedValue( generator="uuid" ) @GenericGenerator( name="uuid", strategy="org.hibernate.id.UUIDGenerator", parameters = { @Parameter( name="uuid_gen_strategy_class", value="org.hibernate.id.uuid.CustomVersionOneStrategy" ) } ) public UUID id; ... }