EntityManager checks the current persistence context (as a kind of first level cache) before going to the database. When you call persist()
you're adding to that context.
Here's the find()
javadoc (emphasis mine):
Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.
and contains()
:
Check if the instance is a managed entity instance belonging to the current persistence context.
In contrast, your named query must access the database, which at this point knows nothing about your cached entity. As you noticed you need to sync your cache with the database by calling flush()
.