I've set up a small project using apache.JDO /w DataNucleus. I can save data w/o any problems, but I got stuck when trying to update or delete them.
The scenario is the following:
- I create an object & persist it, it gets and id
@PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id;
- I close the PersistenceManager
- In the app I modify my object (Transient)
- I try to persist again (the id field is the same), but instead of update it results in the creation of a new object
In Google App Engine the same scenario gave me an update (the expected results - see below).
I will also give you a small code sample to exemplify my problem:
Persiste开发者_开发技巧nceManager pm = PMF.getPM(); Option dao = new Option(String.class, "field", "A"); pm.makePersistent(dao); pm.close(); System.out.println("1"); for (Object o : Model.findAll(Option.class)) System.out.println(((Option) o).getValue()); dao.setValue("B"); pm = PMF.getPM(); pm.makePersistent(dao); pm.close(); System.out.println("2"); for (Object o : Model.findAll(Option.class)) System.out.println(((Option) o).getValue()); pm = PMF.getPM(); pm.makePersistent(dao); pm.deletePersistent(dao); pm.close(); System.out.println("3"); for (Object o : Model.findAll(Option.class)) System.out.println(((Option) o).getValue());
I would expect the output to be:
1 A 2 B 3
But instead it gives me:
1 A 2 A B 3 A B
Any suggestions on what am I doing wrong? (btw I use non-transactional RW, with RetainValues enabled)
I've solved my problem (@point 2)
pm = PMF.getPM(); dao = pm.getObjectById(DO.class, 1L); dao.setValue("B"); pm.makePersistent(dao); pm.close();
But this solutions is somewhat costly if I have 70-100 fields, because I have to set each separately.
I haven't done it manually, but with reflection - but then what's the advantage of DataNucleus over Hibernate? - which (as far as I know) also uses runtime introspection.
Please correct me if I'm wrong - I'm still a newbie in this area... yet :)
You don't need to call makePersistent
agian.
long id = objectId; //Id of the object you want to update.
pm = PMF.getPM();
DO dao = pm.getObjectById(DO.class, id);
dao.setValue("B");
pm.close();
To delete do this;
long id = objectId; //Id of the object you want to delete.
pm = PMF.getPM();
DO dao = pm.getObjectById(DO.class, id);
pm.deletePersistent(dao);
pm.close();
You are not using transaction to commit. You can look at DataNucleus docs
精彩评论