Results 1 to 3 of 3
  1. #1
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default EntityExistsException

    The javadoc for EntityManager.persist(...) says it throws a EntityExistsException if the entity already exists. Does "already exists" mean that if I accidentally create a new entity object with a duplicate primary key, the EntityManager will throw an exception when I try to persist it? What if the key exists in the database, but that particular EM is not currently managing the associated object?

    I know, I could just test it with my JPA provider... but I want to know what the contract is.
    Get in the habit of using standard Java naming conventions!

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: EntityExistsException

    The Managers are associated with the general context I think, so another EntityManager should also "see" the same set of entities.
    At least, presuming they are in the same system (of course).

    So it's not the EM that actually manages them, but the context that sits behind them (at least as far as tracking the entities in the system).

    As far as the key existing in the database, but not necessarily read out into the context, then you won't see the exception until the flush or commit. In other words until the end of the transaction.

  3. #3
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: EntityExistsException

    It's been a while since I used JPA, and I had forgotten about the differences between persist() and merge(). I rediscovered this helpful article that reassures me I cannot accidentally "overwrite" an existing entity with a new one. (I could still clobber data with a merge, but I'm not worried about that right now.)
    Get in the habit of using standard Java naming conventions!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •