30 August 2013

What to do when Play Framework save() do not actually save in database

Solution for Play Framework 1.2.x


STORY
I working at the moment on very excited project that uses Play 1.2, Camel, Guice and lot of black magic.
Surprisingly ,they do not work perfectly well with each other and they cause few troubles.

First major  problem was with error message "The JPA context is not initialized due fact that I tried to use JPA during Play's startup stage.

Solution was using:
  play.Play.plugin(JPAPlugin.class).startTx(true);
    (jpa stuff)
  play.Play.plugin(JPAPlugin.class).closeTx(false);

which didn't work for while until i ... restart STS.
Anyway,problem solved.
Time to move on.
So everything almost works,except
epicItem.save() and .....
nothing happen in database.

SOLUTIONS:

There possible 3 solutions:

I tried this solution ...
http://pareis.com/2011/04/26/beware-of-this-play-frameworks-cascaded-save-only-works-on-loaded-collections/

where Andre Pareis said  cascaded save() only works on loaded collections, so he suggestion solution:
item.positions.size();
item.save();

I didn't use collection in this case,so guess what?
When I tried this solution ....
Nothing happens :).

I didn't give up .I have done more research and I found this:
http://stackoverflow.com/questions/8488565/play-framework-immediate-save

where Dominik Dorn wrote that if you want save immediately ,then you need do:
JPA.em().flush();
JPA.em().getTransaction().commit();
This solution works for me!

It works,but it not fixes a problem,why ? Look of my code
  play.Play.plugin(JPAPlugin.class).startTx(true);
    (jpa stuff)
  play.Play.plugin(JPAPlugin.class).closeTx(false);

 .startTx(true) -I didn't check carefully and  true means  ... read only,which means ..it ignores my save()  !
so... I needed to change .startTx(false)

Conclusions:
  1. Make sure ,that your current transactions is not in read only mode!
  2. If you use cascade operation.Make sure ,that all essential collections are loaded.
  3. In case of emergency use:  JPA.em().flush(); JPA.em().getTransaction().commit(); 
  4. Be careful,when you do 'try everything,so maybe something will works'
I hope that helps

btw. It another time,when i solve Play Framework issue 10 minutes before end of the work, which I found annoying as I fight half day and I feel so upset.It seems I don't have luck with Play 1.2 and JPA stuff :/

Sources:
http://pareis.com/2011/04/26/beware-of-this-play-frameworks-cascaded-save-only-works-on-loaded-collections/
http://stackoverflow.com/questions/8488565/play-framework-immediate-save


No comments:

Post a Comment