java - JPA entities management in a desktop application where object are used to keep modification state -
i'm introducing jpa in existing desktop application persistence layer objects extracted db , stored using plain queries.
after object extracted, used in ui side show , keep user edits. when user press "save" button persistence layer invoked passing object , stored in db. if user press "cancel" button modification throw away , nothing happens in persistence layer.
i'm replacing plain query mechanism jpa. problem when object retrieved using jpa managed. when user modify it, changes stored directly in db.
i can't modify ui code new persistence layer (jpa based) should emulate old persistence layer (plain query based) behaviour.
how can obtain it?
i thinking detach objects before returning them persistence layer. in case user modifications not persisted until persistence layer invoked.
in order detach object can:
- invoke detach method in entitymanager. solution requires annotate relationships related object detached.
- clear entitymanager after each persistence layer operation.
is detach solution right? detach method better?
yes, use case detach
method addresses , go first of 2 approaches, latter seems little extreme , might have performance implications.
you should wary of lazy loaded relationships , make sure required objects have been initialised before detach object , expose presentation layer or you'll come against dreaded lazyinitialisationexception
.
if you're using hibernate implementation (and you're not concerned having pure jpa implementation) following might prove useful in making sure relationships loaded before detach:
public static <t> t initializeandunproxy(t entity) { if (entity == null) { return null; } if (entity instanceof hibernateproxy) { hibernate.initialize(entity); entity = (t) ((hibernateproxy) entity).gethibernatelazyinitializer().getimplementation(); } return entity; }
Comments
Post a Comment