Employee employee = entityManager.find(Employee.class, 1L);
if (employee == null) {
throw new EntityNotFoundException();
}
Since EntityManager#find()
returns null
in case, the said entity is unavailable, the conditional test as shown above is necessary to avoid the possible java.lang.NullPointerException
which is otherwise likely. Repeating this trivial conditional test everywhere is pretty much unacceptable and discouraged which makes the business logic which should in turn be as simple as possible, pretty much unreadable.
To prevent this conditional check from being repeated all over the place, I have a generic method in a separate EJB like so,
@Stateless
public class EntityManagerUtils implements EntityManagerService {
@PersistenceContext
private EntityManager entityManager;
@Override
public <T extends Object> T find(Class<T> entityClass, Object primaryKey) {
T entity = entityManager.find(entityClass, primaryKey);
if (entity == null) {
throw new EntityNotFoundException();
}
return entity;
}
}
Invoking this method from inside another EJB like the following,
@Stateless
public class TestBean implements TestBeanService {
@PersistenceContext
private EntityManager entityManager;
@Inject
private EntityManagerService entityManagerService;
@Override
public void test(Employee employee) {
Department managedDepartment = entityManagerService.find(Department.class, employee.getDepartment().getDepartmentId());
System.out.println("contains : " + entityManager.contains(managedDepartment));
}
}
Here, despite the fact that everything happens within the same single transaction, entityManager.contains(managedDepartment)
returns true
i.e. the returned Department
entity is managed by both the EntityManager
s in both the EJBs.
Although it is expected, how does entityManager.contains(managedDepartment)
return true?
Is it the same EntityManager
instance using the same EntityManagerFactory
?