休眠不尊重MySQL的auto_increment主键字段 [英] Hibernate not respecting MySQL auto_increment primary key field

查看:100
本文介绍了休眠不尊重MySQL的auto_increment主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习Hibernate是如何工作的,而且我正陷入几乎无法接受的学习曲线。我看不到如何让Hibernate遵守我的对象的auto_increment策略。相反,它是用现有ID覆盖数据库中的条目,从1开始。



我有一个简单的 Foo

$ b

  CREATE TABLE`Foo`(
`fooId` int() 11)NOT NULL AUTO_INCREMENT,
PRIMARY KEY(`fooId`),

我已经确认用SQL插入多个Foo对象(插入到Foo values(); )是正确的。



My Java类具有使用如下注释指定的ID:

  @Id 
@GeneratedValue (strategy = GenerationType.AUTO)
@Column(name =fooId)
private Integer id;

然后执行一些简单的实例化Foo对象并将它们保存到数据库的测试代码(使用 session.save(OBJ))。看起来它使用自己的主键序列,从一开始,而不是看表的关键策略。它覆盖了那里的所有内容。

我尝试过 @GeneratedValue 位的变体(使用所有可能的策略,离开关闭括号内的条款)。有人甚至建议完全放弃 GeneratedValue 。似乎没有任何工作。



我是否要留下一些东西?我错过了什么? Hibernate真的很难吗?



(如果有人有另一种Java数据库持久性选项,请提出一个建议,我正在制作原型,而不是长久的mondo-engineered项目。 )

解决方案

我相信你想要 GenerationType.IDENTITY 。 MySql不使用表或序列来生成Id值。


I am trying to learn how Hibernate works, and I am running into an almost unacceptable learning curve. I can't see how to get Hibernate to respect the auto_increment policy for my objects. Instead, it is overwriting entries in the database with existing IDs, beginning with 1.

I have a simple Foo object, backed by a MySQL table defined like this:

CREATE TABLE `Foo` (
  `fooId` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`fooId`),
)

I have confirmed that inserting multiple Foo objects by hand with SQL (insert into Foo values();) does the right thing.

My Java class has the ID specified using annotations like this:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="fooId")
private Integer id;

I then execute some test code that simply instantiates Foo objects and saves them to the database (using session.save(obj)). It seems that it uses its own primary key sequence, beginning with one, and does not look at the table's key policy. It overwrites whatever was there.

I have tried variations on the @GeneratedValue bit (using all possible strategies, leaving off the parenthetic clause). Somebody even suggested leaving off the GeneratedValue entirely. Nothing seems to work.

Am I leaving something out? What am I missing? Is Hibernate really this hard?

(If anybody has an alternative Java database persistence option, please suggest one. I am making prototypes, not long-lasting mondo-engineered projects.)

解决方案

I believe you want GenerationType.IDENTITY. MySql does not use a table or sequence for generating the Id value.

这篇关于休眠不尊重MySQL的auto_increment主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆