EntityManager#contains(Object) Rolls Back the Transaction

A note for posterity: if you call EntityManager#contains(Object) on an object that is not known to that EntityManager, it will throw an IllegalArgumentException. When it does so, it irrevocably rolls the transaction back.

Instead, use something like this:

* 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;

view raw
hosted with ❤ by GitHub