Define classes that will modify or search for entities

Define classes that will modify or search for entities

The OrderServiceSupport (In LOGISTICX/order/order-ws-su/src/ directory) and OrderProcessortSupport (In LOGISTICX/order-processor/order-processor-su/src/ directory) helper classes in the Logistics demo persist and modify the Order and OrderStatus entities.

1) Obtaining an Entity Manager

Obtaining an EntityManagerFactory will be vendor specific. In this use case we will use the Peristence class that is a bootstrap class that is used to obtain an EntityManagerFactory. In the classpath resources directory the persistence class will search for the persistent provider files in the <meta-inf/services/directory>. It reads the persistent providers implementation class names for each file and calls the create EntityManagerFactory() on each with the persistent-unit-name until it gets back an entity manager.

The EntityManager is the primary interface used by application developers to interact with the JPA runtime.  It manages entities and is reponsible for their addition, updating, and deletion. You can find an entity without a transaction, but any modification operations need to be within a transaction.  If you don't use transaction management, the entity won't become managed and everytime you fetch a record from the database you will get a separate object.

Example 1.4 EntityManager

....

 EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("order-processor");
 EntityManager em = emFactory.createEntityManager();
 em.getTransaction().begin();

 ....

Every EntityManager has a One-to-One relation with an EntityTransaction instance. You can retrieve an EntityTransaction associated with an EntityManager through the getTransaction method.

2) Persisting Objects.

The persist method transitions new instances to be managed. On the next flush or commit, the newly persisted instances will be inserted into the datastore.

Example 1.5 Persist method

private void doJpaPersist(Object object){
    try {
        em.getTransaction().begin();
        if (object instanceof Order) {
            em.persist((Order) object);
        } else {
            em.persist((OrderStatus) object);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        em.getTransaction().commit();
    }
}

For a given entity A, the persist method behaves as follows:

  • If A is a new entity, it becomes managed.
  • If A is an existing managed entity, it is ignored. However, the persist operation cascades as defined below.
  • If A is a removed entity, it becomes managed.

3) Fetching Objects

To find a record that was inserted use the primary key that was generated.

Example 1.6 Find method

OpenJPAEntityManager em =&nbsp; OpenJPAPersistence.cast(em);
Object objId = em.getObjectId(Order);
Order cust = em.find(Order.class, objId);
....

Because the primary key is unknown up front, the application must cast EntityManager to OpenJPAEntityManager to get the primary key object by passing the Order object that was persisted earlier.

Use may also use a JPA Query

Example 1.7 JPA Query String

/* A JPA query to retrieve the order status based on the order id. */
  private static final String ORDERSTATUS_QUERY = "select stat from com.iona.fuse.demo.logisticx.model.OrderStatus stat where stat.order.orderId = ?1";
  • The EntityManager.createQuery method creates a Query instance from a given JPQL string.
  •  A JPQL query has an internal namespace declared in the from clause of the query. Arbitrary identifiers are assigned to entities so that they can be referenced elsewhere in the query. In the ORDERSTATUS_QUERY above, the identifier stat is assigned to the entity OrderStatus.
  • Following the select clause of the query is the object or objects that the query returns.
  • The getSingleResult() method executes a SELECT query that returns a single result.
  • The WHERE clause of a query consists of a conditional expression used to select objects or values that satisfy the expression. The WHERE clause restricts the result of a select statement or the scope of an update or delete operation. Here it will only return the OrderStatus where the OrderId matches the OrderId in the Query.

Example 1.8 Execute JPA Query

private OrderStatus doJpaRestrieve(Long orderId) {
    OrderStatus status = null;
    try {
        ....
        Query orderQuery = em.createQuery(ORDERSTATUS_QUERY);
        orderQuery.setParameter(1, orderId);
        status = (OrderStatus) orderQuery.getSingleResult();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        em.getTransaction().commit();
    }
    return status;
}

4) Updating Objects

It is important to remember the relationship between entities. For example if Cascade.ALL is set - all updates will be refreshed in related entities.

Example 1.9 Updating persisted object

private boolean doJpaRestrieveUpdateOrderStatus(Long orderId, StatusCode statusCode) {
    OrderStatus status = null;
    try {
        ....
        Query orderQuery = em.createQuery(ORDERSTATUS_QUERY);
        orderQuery.setParameter(1, orderId);
        status = (OrderStatus) orderQuery.getSingleResult();
        status.setStatusCode(statusCode);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        em.getTransaction().commit();
    }
    return true;
}

Labels

 
(None)