Hibernate version: 3.1.2
Mapping documents:
Code:
<class name="reger.dao.hibernate.Image" table="image">
<cache usage="nonstrict-read-write"/>
<id name="imageid" type="int">
<column name="imageid" />
<generator class="assigned" />
</id>
...
</class>
Code between sessionFactory.openSession() and session.close():Code:
//Create a transient Image object
Image newimage = new Image();
newimage.setFilename("myfile.jpg");
newimage.setEventid(eventid);
Session hsession = HibernateUtil.getSession();
hsession.beginTransaction();
//Convert it to a persistent object
hsession.save(newimage);
hsession.getTransaction().commit();
//Problem here: imageid is reported as 0 after save.
System.out.println("imageid=" + newimage.getImageid());
hsession.close();
Name and version of the database you are using:
MySql 5.0
The generated SQL (show_sql=true):
Hibernate: insert into image (eventid, accountuserid, image, description, sizeinbytes, imageorder, originalfilename, accountid, filename, imageid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Problem description:
I create a transient instance of Image called newimage. At this point the identifier (imageid) is, of course, 0. I expect this.
I then call save() on the instance, converting it from transient to persistent. The database is correctly updated and an imageid>0 is generated by MySql auto increment. The row appears properly in the database.
However, when I then call newimage.getImageid() I get 0. I would expect to get the new imageid that the database has assigned.
Questions:
1) Am I wrong to expect that the persistent object will reflect the identifier value after being converted from a transient with the save() method?
2) How can I get the identifier of a newly-persisted object? I've tried calling hsession.refresh(newimage) after save() but am told that a row with imageid=0 does not exist in the database. Makes sense as the imageid is not populated on save(), but I'm hoping there's a way to get the new id.
3) I'm caching the Image class... is there anything special I need to do to get the identifier after a conversion from transient to persistent when the class is cached?
Thanks all!
Joe