public void edit(Room room) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Room persistentRoom = em.find(Room.class, room.getId()); Department departmentOld = persistentRoom.getDepartment(); Department departmentNew = room.getDepartment(); Category categoryOld = persistentRoom.getCategory(); Category categoryNew = room.getCategory(); if (departmentNew != null) { departmentNew = em.getReference(departmentNew.getClass(), departmentNew.getId()); room.setDepartment(departmentNew); } if (categoryNew != null) { categoryNew = em.getReference(categoryNew.getClass(), categoryNew.getId()); room.setCategory(categoryNew); } room = em.merge(room); if (departmentOld != null && !departmentOld.equals(departmentNew)) { departmentOld.getRoomCollection().remove(room); departmentOld = em.merge(departmentOld); } if (departmentNew != null && !departmentNew.equals(departmentOld)) { departmentNew.getRoomCollection().add(room); departmentNew = em.merge(departmentNew); } if (categoryOld != null && !categoryOld.equals(categoryNew)) { categoryOld.getRoomCollection().remove(room); categoryOld = em.merge(categoryOld); } if (categoryNew != null && !categoryNew.equals(categoryOld)) { categoryNew.getRoomCollection().add(room); categoryNew = em.merge(categoryNew); } em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = room.getId(); if (findRoom(id) == null) { throw new NonexistentEntityException("The room with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public void create(Room room) throws RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Department department = room.getDepartment(); if (department != null) { department = em.getReference(department.getClass(), department.getId()); room.setDepartment(department); } Category category = room.getCategory(); if (category != null) { category = em.getReference(category.getClass(), category.getId()); room.setCategory(category); } em.persist(room); if (department != null) { department.getRoomCollection().add(room); department = em.merge(department); } if (category != null) { category.getRoomCollection().add(room); category = em.merge(category); } em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }