2015-09-06 76 views
9

所以我刚刚下载了hibernate 5.0.0.1,并且我尝试了我的项目,它以前使用hibernate 4.3。hibernate创建空表 - hibernate_sequence在启动时

当我插入到数据库中,它给了我这个错误:

ERROR: could not read a hi value - you need to populate the table: hibernate_sequence

我使用MySQL和我这一代的策略设定在GenerationType.auto,它似乎是现在使用休眠序列跟着感觉走创造价值的最佳策略。但桌子是空的。我认为hibernate试图从序列中获取一个值,但找不到任何值。但我很困惑,因为hibernate_sequence是由hibernate创建的,它不应该提供初始值吗?

回答

15

序列表是因为您如何定义了一个/所有实体上的主键。

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) // or GenerationType.SEQUENCE 
protected Long id; 

如果你想使用一个表的身份列:

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
protected Long id; 

你可能要检查这个线程的详细信息: https://forums.hibernate.org/viewtopic.php?f=1&t=999785&start=0

@GeneratedValue JPA Annotation

Quite often in these tutorials, we have used the @GeneratedValue annotation to have thedatabase generate a unique primary key for us. We have used the default Generation Type in each of our examples, but there are actually four different strategies for having the primary key generated by the database. Those four options are:

AUTO IDENTITY TABLE SEQUENCE javax.persistence.GenerationType.AUTO

The AUTO generation strategy is the default, and this setting simply chooses the primary key generation strategy that is the default for the database in question, which quite typically is IDENTITY, although it might be TABLE or SEQUENCE depending upon how the database is configured. The AUTO strategy is typically recommended, as it makes your code and your applications most portable.

javax.persistence.GenerationType.IDENTITY

The IDENTITY option simply allows the database to generate a unique primary key for your application. No sequence or table is used to maintain the primary key information, but instead, the database will just pick an appropriate, unique number for Hibernate to assign to the primary key of the entity. With MySQL, the first lowest numbered primary key available in the table in question is chosen, although this behavior may differ from database to database.

javax.persistence.GenerationType.Sequence

Some database vendors support the use of a database sequence object for maintaining primary keys. To use a sequence, you set the GenerationType strategy to SEQUENCE, specify the name of the generator annotation, and then provide the @SequenceGenerator annotation that has attributes for defining both the name of the sequence annotation, and the name of the actual sequence object in the database.

+1

但我的策略设置为自动创建的,我想我会使用hibernate认为是最好的策略。但我怎么能通过休眠来填充序列? – morbidCode

+2

上面报价中的最后一项说明了这一切。老实说,除非IDENTITY不适合你,否则不要使用AUTO。大多数数据库支持每个表的唯一标识符。 –

1

Simple solution :

创建hibernate_sequence表作为:

"create sequence <schema/db>.hibernate_sequence" 
1

这是因为使用Hibernate该表来跟踪自动增量ID(该ID的下一个值)

EX-

@Id 
@GeneratedValue 
int id;