Social Media

EntityManager

This section is a walkthru of the methods in EntityManager

All of these methods require –

  • Persistence context
  • Action only completed when complete or flushed
  • Requires Transaction Context
  • Only work on @Entity
  • Doesnt work on @Embeddable

EntityManager.close()

  • Close EntityManager

EntityManager.flush()

  • Write changes to DB before Transaction Committed
  • Uses – populate Ids, clear batches during batch processing

EntityManager.getDelegate()

  • Access Underlying EntityManager implementation

EntityManager.getReference()

  • Get object placeholder without loading object – gives performance advantages
  • Stand-in for related object
  • Does not verify existence of object on datastore – so could result in foreign key constraint

AgreementState agreementState = entityManager.getReference(AgreementState.class, agreementStateId);
Agreement agreement = new Agreement();

entityManager.persist(agreement);
agreement.setAgreementState(agreementState);

entityManager.commit();

EntityManager.merge()

  • merges into persistence context
  • Normally called for existing objects
  • Only Entity objects, not Embeddable

Agreement managementAgreement = em.merge(detachAgreement);

EntityManager.persist()

  • Called within transaction
  • Inserts new @Entity object into datastore
  • Registers with EntityManager
  • Id assigned when persist() called

Agreement agreement = new Agreement();
agreement.setAgreement(“Test name”);
entityManager.persist(agreement);

EntityManager.refresh()

  • Refresh Managed Object with whats currently on database
  • Not for detached objects

entityManager.refresh(refreshAgreement);

EntityManager.remove()

  • Delete object

Agreement agreementToBeDeleted = entityManager.find(Agreement.class, agreementId);
entityManager.remove(agreementToBeDeleted);

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment:

1 comment
Add Your Reply