views:

181

answers:

1

I am using datanucleus and jdo in a GWT project. How can I retrieve the generated primary key after adding an element to the database with makePersistent()

Edit We use annotations, here is the primary key:

    @PrimaryKey
@Column(name = "id_bla", allowsNull = "false")
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY, extensions = { @Extension(vendorName = "datanucleus", key = "strategy-when-notnull", value = "false") })
private Long idBla;

I am not the one who did the mapping and I don't get all of this yet.

A: 

The object's key should be automatically set when it is persisted:

MyObject obj = new MyObject();
Long id = obj.getId();  // WRONG! Will still be null.
pm.makePersistent(obj);
id = obj.getId();  // Correct.
Todd Owen
Thanks for the answer. That's the behavior I expected but after my "makePersistent(obj)" my obj.getId() is still null... While the id in the DB is correctly generated and all other data is saved normally.
DrDro
Are you using annotations or XML? If the ID appears in the database then the annotations (like identityType, valueStrategy, etc) are presumably correct. Does getObjectById() work? Check for typos in getId()!
Todd Owen
I use annotations (I've edited my post). It is the DB who generates the ID so that my be the reason I can't retrieve it just after the makePersitent. I just tried getObjectById() with an ID from the DB but I get a "No such database row" exception. When I query all the results though the IDs are retrieved properly.
DrDro
Those annotations look correct - IdGeneratorStrategy.IDENTITY indicates that JDO should allow the database to generate the ID). Is your class also annotated @PersistenceCapable(identityType=IdentityType.APPLICATION)? Finally, see what value is returned by pm.getObjectId(obj) after obj has been persisted.
Todd Owen