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.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…