Last active
December 21, 2015 21:08
-
-
Save ljnelson/6366032 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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