Skip to content

Instantly share code, notes, and snippets.

Last active Dec 21, 2015
What would you like to do?
A method showing how to test to see if an EntityManager contains an arbitrary object, not just a known entity, without running the risk of rolling the transaction back.
* Returns {@code true} if the supplied {@link EntityManager} is
* non-{@code null} and contains the supplied {@link Object} in its
* persistence context. Unlike the {@link EntityManager#contains(Object)}
* method, this method will not throw any exceptions, and hence will
* never roll the containing transaction back.
* @param em the {@link EntityManager} in question; may be {@code null}
* in which case {@code false} will be returned
* @param o the {@link Object} to look for; may be {@code null} in which
* case {@code false} will be returned
* @return {@code true} if the supplied {@link Object} is a {@linkplain
* Metamodel#getManagedTypes() managed type} with respect to the supplied
* {@link EntityManager} and is also {@linkplain
* EntityManager#contains(Object) contained} by the supplied {@link
* EntityManager}; {@code false} otherwise
public static final boolean contains(final EntityManager em, final Object o) {
boolean returnValue = false;
if (em != null && o != null) {
final Metamodel mm = em.getMetamodel();
if (mm != null) {
final Collection<?> types = mm.getManagedTypes();
returnValue = types != null && types.contains(o) && em.contains(o);
return returnValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment