0

I wonder if these methods are equivalent when shared cache is disabled:

@Stateless
public class EntityService
{
    @PersistenceContext
    private EntityManager em;

    public <T> T findEntity1(Class<T> clazz, long id)
    {
        return em.find(clazz, id);
    }

    public <T> T findEntity2(Class<T> clazz, long id)
    {
        T entity = em.find(clazz, id);
        em.refresh(entity);
        return entity;
    }
}

These methods are never called inside an existing transaction. The db is exclusively accessed by this application using only JPA and no trigger/stored procedure/other is defined.

My guess is they are equivalent, because:

  • em.find() will search the shared cache (L2), but it's empty (disabled)
  • em.find() will search its own cache (L1), but it's empty (no previous transaction = em is new)
  • em.find() will access db
  • em.refresh() will access db a second time, but in this scenario the entity is always the same

Did I miss something?

Michele Mariotti
  • 7,372
  • 5
  • 41
  • 73
  • 1
    You miss that your bean has by default `@TransactionAttribute(REQUIRED)` you have a new transaction when no exists. For the other points i think you are right. – pL4Gu33 May 31 '15 at 11:04
  • 1
    "eventually" access db ? If you call EntityManager#refresh(Object) you are instructing ORM to access the db a 2nd time. Yes the entity maybe the same but the ORM doesn't know that until it accesses the db (for example hybrid SQL server features that modify data inside SQL transactions, trigger on SELECT increments counter, that the ORM doesn't know about). Your use of the word "eventually" maybe that you can observe your ORM implementation delay this 2nd SQL access until such time as a potentially dirty property is read through the entity proxy. Performance wise the methods are not the same. – Darryl Miles Jun 01 '15 at 05:45
  • @pL4Gu33 right, i added *no previous transaction* – Michele Mariotti Jun 01 '15 at 10:10
  • @DarrylMiles that's not my scenario, now I've specified it and I've corrected the "eventually". Performace is a difference, nevertheless these operations seems to be conceptually equivalent as they always return the same thing. – Michele Mariotti Jun 01 '15 at 10:20

0 Answers0