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.

我正在努力学习Hibernate的工作原理,并且我遇到了几乎无法接受的学习曲线。我看不出如何让Hibernate尊重我的对象的auto_increment策略。相反,它使用现有ID覆盖数据库中的条目,从1开始。

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

我有一个简单的Foo对象,由如下定义的MySQL表支持:

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.

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

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

我的Java类使用如下注释指定了ID:

@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.

然后我执行一些测试代码,简单地实例化Foo对象并将它们保存到数据库中(使用session.save(obj))。它似乎使用自己的主键序列,从一开始,并没有查看表的关键策略。它会覆盖那里的一切。

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.

我已经尝试了@GeneratedValue位的变体(使用所有可能的策略,不考虑括号子句)。有人甚至建议完全放弃GeneratedValue。似乎没什么用。

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

我要留下什么了?我错过了什么? Hibernate真的很难吗?

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

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

5 个解决方案

#1


28

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

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

更多相关文章

  1. 求问vs窗体应用程序用gridview连接mysql未能获取数据库对象的列
  2. javascript判断数组和对象中是否存在某元素
  3. 如何将对象作为参数传播给函数?
  4. RangeError:在Node.js中调试/记录/检查对象时超过了最大调用堆栈
  5. 是否有一个简单的库将JSON对象渲染为树?
  6. 在JavaScript中进行文件处理,第四部分:对象URLs
  7. 我在显示随机选择的对象时遇到问题
  8. 如何在JavaScript / jQuery中获取对象的属性?
  9. 【JavaScript】JavaScript的对象-对象专门语句

随机推荐

  1. android卡片布局CardView
  2. Android高级知识—思维导图
  3. Android查看内存和CPU~
  4. Android获取 应用程序大小,数据大小,缓存大
  5. Android 实现 按钮从两边移到中间动画效
  6. android的KeyGuard
  7. Android(安卓)SDK更新后 ADT R17 E/Andro
  8. android xml 常用控件介绍
  9. android 创建动态创建菜单(钩子)
  10. android 开启本地相册选择图片并返回显示