JPA - PersistenceUtil.isLoaded Examples

Code Snippets JPA JAVA EE 

    static void printLoadState(String msg, Employee employee) {
System.out.printf("-- %s --%n", msg);
PersistenceUtil pu = Persistence.getPersistenceUtil();
boolean employeeLoaded = pu.isLoaded(employee);
System.out.printf("employee loaded: %s%n", employeeLoaded);
boolean phonesLoaded = pu.isLoaded(employee, "phones");
System.out.printf(" phones loaded: %s%n", phonesLoaded);
System.out.println("---------------");
}
Original Post




    private static Employee checkAndInitialize(Employee employee) {
PersistenceUtil pu = entityManagerFactory.getPersistenceUnitUtil();
System.out.println(" Employee loaded: " + pu.isLoaded(employee));
System.out.println("Employee.phones loaded: " + pu.isLoaded(employee, "phones"));
if (!pu.isLoaded(employee) //entity might've been retrieved via getReference
|| !pu.isLoaded(employee, "phones")//phones is a lazy relation
) {
System.out.println("initializing employee");
boolean detached = !entityManager.contains(employee);
System.out.println("is employee detached: " + detached);
if (detached) {
System.out.println("merging employee");
employee = entityManager.merge(employee);
}
//this will load/initialize employee entity
employee.getName();
employee.getDepartment();
//this will load lazy phones field
employee.getPhones().size();
entityManager.detach(employee);
//now employee is fully initialized
System.out.println("employee initialized");
}
return employee;
}
Original Post




See Also