Here is a trick I use:
I have a version field (@Version annotation), it is an Integer (NOT int). If
the Entity has never been in persistent storage, the version is null. It
also improves performance under moderate to high loads.
ax/
2009/1/27 sonavor <jw_at_worleytown.com>
>
> It seemed easier in my situation to delete everything and re-insert. I did
> go ahead and do an update (and that works) but I had to add a bunch of
> logic
> that checks if some of records are new (so are straight inserts) or exist
> (and are updates) or exist and need to be removed. I was hoping to not
> have
> to write all of that logic and just delete the existing records then insert
> with the new data that is passed in.
>
>
>
> Axl Mattheus-2 wrote:
> >
> > Why do you delete the entity and not update it instead?
> > ...
> > anEntity.setValue(whatever);
> > em.merge(anEntity);
> > ...
> >
> >
> > 2009/1/24 sonavor <jw_at_worleytown.com>
> >
> >>
> >> I am having trouble trying to resolve a problem with an application that
> >> uses
> >> an EJB 3 stateless session EJB as a DAO for some JPA entity beans. For
> >> one
> >> business rule I need a method in the session EJB to delete existing
> >> entity
> >> beans for a submitted key and insert a new set of entity beans passed to
> >> the
> >> method. It is possible and likely that some of the new entity beans
> >> could
> >> have a primary key that is the same as one of the deleted entities.
> >>
> >> I tried this -
> >>
> >> MyEntityTestPK e1PK = new e1PK(someValue1, someValue2);
> >>
> >> MyEntity1 anEntity = em.find(MyEntity1.class, e1PK);
> >> if ( anEntity != null ) {
> >> em.remove(anEntity);
> >> }
> >>
> >> ...later in the same method I insert an entity -
> >>
> >> MyEntity1 anotherEntity = new MyEntity();
> >> anotherEntity.setPk(e1PK);
> >> anotherEntity.setValue1(somevalue)
> >>
> >> em.persist(anotherEntity);
> >>
> >> ...This produces an exception complaining of a duplicate key. I also
> >> tried
> >> doing a merge but that generates a "cannot persist detached object"
> >> exception.
> >>
> >> What are the proper steps to delete records then create records again in
> >> the
> >> same transaction with (occasionally) the same primary key value?
> >>
> >>
> >> --
> >> View this message in context:
> >>
> http://www.nabble.com/JPA-with-EJB3---remove-an-entity-and-create-new-entity-with-same-primary-key-%28same-transaction%29-tp21639342p21639342.html
> >> Sent from the java.net - glassfish persistence mailing list archive at
> >> Nabble.com.
> >>
> >>
> >
> >
>
> --
> View this message in context:
> http://www.nabble.com/JPA-with-EJB3---remove-an-entity-and-create-new-entity-with-same-primary-key-%28same-transaction%29-tp21639342p21673999.html
> Sent from the java.net - glassfish persistence mailing list archive at
> Nabble.com.
>
>