public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); TipoEstadoNormatividad tipoEstadoNormatividad; try { tipoEstadoNormatividad = em.getReference(TipoEstadoNormatividad.class, id); tipoEstadoNormatividad.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The tipoEstadoNormatividad with id " + id + " no longer exists.", enfe); } List<Normatividad> normatividadList = tipoEstadoNormatividad.getNormatividadList(); for (Normatividad normatividadListNormatividad : normatividadList) { normatividadListNormatividad.setIdEstado(null); normatividadListNormatividad = em.merge(normatividadListNormatividad); } List<SeguimientoNormatividad> seguimientoNormatividadList = tipoEstadoNormatividad.getSeguimientoNormatividadList(); for (SeguimientoNormatividad seguimientoNormatividadListSeguimientoNormatividad : seguimientoNormatividadList) { seguimientoNormatividadListSeguimientoNormatividad.setIdEstado(null); seguimientoNormatividadListSeguimientoNormatividad = em.merge(seguimientoNormatividadListSeguimientoNormatividad); } em.remove(tipoEstadoNormatividad); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void edit(CategHabitacion categHabitacion) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); CategHabitacion persistentCategHabitacion = em.find(CategHabitacion.class, categHabitacion.getCodigoCategoria()); Collection<Habitacion> habitacionCollectionOld = persistentCategHabitacion.getHabitacionCollection(); Collection<Habitacion> habitacionCollectionNew = categHabitacion.getHabitacionCollection(); Collection<Habitacion> attachedHabitacionCollectionNew = new ArrayList<Habitacion>(); for (Habitacion habitacionCollectionNewHabitacionToAttach : habitacionCollectionNew) { habitacionCollectionNewHabitacionToAttach = em.getReference( habitacionCollectionNewHabitacionToAttach.getClass(), habitacionCollectionNewHabitacionToAttach.getNumero()); attachedHabitacionCollectionNew.add(habitacionCollectionNewHabitacionToAttach); } habitacionCollectionNew = attachedHabitacionCollectionNew; categHabitacion.setHabitacionCollection(habitacionCollectionNew); categHabitacion = em.merge(categHabitacion); for (Habitacion habitacionCollectionOldHabitacion : habitacionCollectionOld) { if (!habitacionCollectionNew.contains(habitacionCollectionOldHabitacion)) { habitacionCollectionOldHabitacion.setCodigoCategoria(null); habitacionCollectionOldHabitacion = em.merge(habitacionCollectionOldHabitacion); } } for (Habitacion habitacionCollectionNewHabitacion : habitacionCollectionNew) { if (!habitacionCollectionOld.contains(habitacionCollectionNewHabitacion)) { CategHabitacion oldCodigoCategoriaOfHabitacionCollectionNewHabitacion = habitacionCollectionNewHabitacion.getCodigoCategoria(); habitacionCollectionNewHabitacion.setCodigoCategoria(categHabitacion); habitacionCollectionNewHabitacion = em.merge(habitacionCollectionNewHabitacion); if (oldCodigoCategoriaOfHabitacionCollectionNewHabitacion != null && !oldCodigoCategoriaOfHabitacionCollectionNewHabitacion.equals(categHabitacion)) { oldCodigoCategoriaOfHabitacionCollectionNewHabitacion .getHabitacionCollection() .remove(habitacionCollectionNewHabitacion); oldCodigoCategoriaOfHabitacionCollectionNewHabitacion = em.merge(oldCodigoCategoriaOfHabitacionCollectionNewHabitacion); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = categHabitacion.getCodigoCategoria(); if (findCategHabitacion(id) == null) { throw new NonexistentEntityException( "The categHabitacion with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public void edit(Long altId, Vote vote) throws NonExistingEntityException, RollbackFailureException, Exception { Alternative alternative = em.find(Alternative.class, altId); if (alternative == null) { throw new NonExistingEntityException("Alternative with Id = " + altId + " does not exist"); } vote.setAlternative(alternative); Vote persistentVote = em.find(Vote.class, vote.getId()); Alternative alternativeOld = persistentVote.getAlternative(); Alternative alternativeNew = vote.getAlternative(); if (alternativeNew != null) { alternativeNew = em.getReference(alternativeNew.getClass(), alternativeNew.getId()); vote.setAlternative(alternativeNew); } vote = em.merge(vote); if (alternativeOld != null && !alternativeOld.equals(alternativeNew)) { alternativeOld.getVotes().remove(vote); alternativeOld = em.merge(alternativeOld); } if (alternativeNew != null && !alternativeNew.equals(alternativeOld)) { alternativeNew.getVotes().add(vote); alternativeNew = em.merge(alternativeNew); } }
@POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void putResponse( String userResponse, @PathParam("eventId") Long eventId, @PathParam("inviteId") Long personId) { logger.log( Level.INFO, "Updating status to {0} for person ID {1} for event ID {2}", new Object[] {userResponse, eventId, personId}); Response response = (Response) em.createNamedQuery("rsvp.entity.Response.findResponseByEventAndPerson") .setParameter("eventId", eventId) .setParameter("personId", personId) .getSingleResult(); if (userResponse.equals(ResponseEnum.ATTENDING.getLabel()) && !response.getResponse().equals(ResponseEnum.ATTENDING)) { response.setResponse(ResponseEnum.ATTENDING); em.merge(response); } else if (userResponse.equals(ResponseEnum.NOT_ATTENDING.getLabel()) && !response.getResponse().equals(ResponseEnum.NOT_ATTENDING)) { response.setResponse(ResponseEnum.NOT_ATTENDING); em.merge(response); } else if (userResponse.equals(ResponseEnum.MAYBE_ATTENDING.getLabel()) && !response.getResponse().equals(ResponseEnum.MAYBE_ATTENDING)) { response.setResponse(ResponseEnum.MAYBE_ATTENDING); em.merge(response); } }
public void create(Subgrupos subgrupos) { if (subgrupos.getProcesosList() == null) { subgrupos.setProcesosList(new ArrayList<Procesos>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); List<Procesos> attachedProcesosList = new ArrayList<Procesos>(); for (Procesos procesosListProcesosToAttach : subgrupos.getProcesosList()) { procesosListProcesosToAttach = em.getReference( procesosListProcesosToAttach.getClass(), procesosListProcesosToAttach.getId()); attachedProcesosList.add(procesosListProcesosToAttach); } subgrupos.setProcesosList(attachedProcesosList); em.persist(subgrupos); for (Procesos procesosListProcesos : subgrupos.getProcesosList()) { Subgrupos oldSubgruposIdOfProcesosListProcesos = procesosListProcesos.getSubgruposId(); procesosListProcesos.setSubgruposId(subgrupos); procesosListProcesos = em.merge(procesosListProcesos); if (oldSubgruposIdOfProcesosListProcesos != null) { oldSubgruposIdOfProcesosListProcesos.getProcesosList().remove(procesosListProcesos); oldSubgruposIdOfProcesosListProcesos = em.merge(oldSubgruposIdOfProcesosListProcesos); } } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Clasedatos clasedatos; try { clasedatos = em.getReference(Clasedatos.class, id); clasedatos.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The clasedatos with id " + id + " no longer exists.", enfe); } Entidad entidadId = clasedatos.getEntidadId(); if (entidadId != null) { entidadId.getClasedatosList().remove(clasedatos); entidadId = em.merge(entidadId); } List<Procesos> procesosList = clasedatos.getProcesosList(); for (Procesos procesosListProcesos : procesosList) { procesosListProcesos.getClasedatosList().remove(clasedatos); procesosListProcesos = em.merge(procesosListProcesos); } em.remove(clasedatos); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
@POST @Consumes("application/x-www-form-urlencoded") @Produces("text/html") public String putResponse( @FormParam("attendeeResponse") String userResponse, @PathParam("eventId") Long eventId, @PathParam("inviteId") Long personId) { StringBuilder output = new StringBuilder(); Response response = (Response) em.createNamedQuery("rsvp.entity.Response.findResponseByEventAndPerson") .setParameter("eventId", eventId) .setParameter("personId", personId) .getSingleResult(); Event event = response.getEvent(); Person person = response.getPerson(); if (userResponse.equals("Yes") && !response.getResponse().equals(ResponseEnum.ATTENDING)) { response.setResponse(ResponseEnum.ATTENDING); em.merge(response); } else if (userResponse.equals("No") && !response.getResponse().equals(ResponseEnum.NOT_ATTENDING)) { response.setResponse(ResponseEnum.NOT_ATTENDING); em.merge(response); } else if (userResponse.equals("Maybe") && !response.getResponse().equals(ResponseEnum.MAYBE_ATTENDING)) { response.setResponse(ResponseEnum.MAYBE_ATTENDING); em.merge(response); } // create the response HTML output .append("<html lang=\"en\"><head><title>Current response for ") .append(person.getFirstName()) .append(" ") .append(person.getLastName()) .append(" at ") .append(event.getName()) .append("</title>") .append("<link href=\"/rsvp/css/default.css\" rel=\"stylesheet\" type=\"text/css\" />") .append("</head>"); output.append("<body><h1>").append(event.getName()).append("</h1>"); output .append("<p>Thanks for your RSVP, ") .append(person.getFirstName()) .append(" ") .append(person.getLastName()) .append("!</p>"); output .append("<p>Your current response is: ") .append(response.getResponseText()) .append("</p>"); output .append("<p><a href=\"/jaxrs_rsvp_db/resources/status/") .append(event.getId()) .append("\">Back to event page</a></p>"); output.append("</body></html>"); return output.toString(); }
/** * Elimina un almacen de la base de datos con el <code>id</code> especificado. * * @param id el <code>id</code> del almacen en la base de datos. * @throws NonexistentEntityException Se lanza ésta excepción cuando el almacen que se quiere * eliminar no existe en la base de datos. */ public void destruirAlmacen(Long id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Almacen almacen; try { almacen = em.getReference(Almacen.class, id); almacen.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "El almacen que desea eliminar de la base de datos no existe.", enfe); } Sucursal sucursal = almacen.getSucursal(); if (sucursal != null) { sucursal.getAlmacenes().remove(almacen); sucursal = em.merge(sucursal); } List<LoteAlmacenado> lotesAlmacenados = almacen.getLotesAlmacenados(); for (LoteAlmacenado lotesAlmacenadosLoteAlmacenado : lotesAlmacenados) { lotesAlmacenadosLoteAlmacenado.setAlmacen(null); lotesAlmacenadosLoteAlmacenado = em.merge(lotesAlmacenadosLoteAlmacenado); } em.remove(almacen); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public String performBill() { sender.setCheckingaccount(sender.getCheckingaccount() - amount); recipient.setCheckingaccount(recipient.getCheckingaccount() + amount); em.merge(sender); em.merge(recipient); return sender.getCheckingaccount().toString(); }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Timereport timereport; try { timereport = em.getReference(Timereport.class, id); timereport.getIdtimereport(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The timereport with id " + id + " no longer exists.", enfe); } Utilisateur idutilisateur = timereport.getIdutilisateur(); if (idutilisateur != null) { idutilisateur.getTimereportCollection().remove(timereport); idutilisateur = em.merge(idutilisateur); } Tache idtache = timereport.getIdtache(); if (idtache != null) { idtache.getTimereportCollection().remove(timereport); idtache = em.merge(idtache); } em.remove(timereport); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void testGF1894() { EntityManager em = createEntityManager(m_persistenceUnit); beginTransaction(em); Employee emp = new Employee("Guy", "Pelletier"); Address address = new Address(); address.setCity("College Town"); emp.setAddress(address); try { Employee empClone = em.merge(emp); assertNotNull( "The id field for the merged new employee object was not generated.", empClone.getId()); commitTransaction(em); Employee empFromDB = em.find(Employee.class, empClone.getId()); assertNotNull( "The version locking field for the merged new employee object was not updated after commit.", empFromDB.getVersion()); beginTransaction(em); Employee empClone2 = em.merge(empFromDB); assertTrue( "The id field on a existing merged employee object was modified on a subsequent merge.", empFromDB.getId().equals(empClone2.getId())); commitTransaction(em); } catch (javax.persistence.OptimisticLockException e) { fail( "An optimistic locking exception was caught on the merge of a new object. An insert should of occurred instead."); } closeEntityManager(em); }
@Test @Priority(10) public void initData() { EntityManager em = getOrCreateEntityManager(); try { // Revision 1 em.getTransaction().begin(); NameInfo ni = new NameInfo("John", "Doe"); Person person1 = new Person("JDOE", ni); em.persist(person1); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); person1 = em.find(Person.class, person1.getId()); person1.getNameInfo().setFirstName("Jane"); em.merge(person1); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); person1 = em.find(Person.class, person1.getId()); person1.setName("JDOE2"); em.merge(person1); em.getTransaction().commit(); personId = person1.getId(); } finally { em.close(); } }
// extract from inventory public int checkInventory(String sku, String color, String size, int quantity) { InventoryPK pk = new InventoryPK(sku, color, size); Inventory inventory = em.find(Inventory.class, pk, LockModeType.OPTIMISTIC); int amount = inventory.getInventory(); if (amount > 0) { if (amount >= quantity) { amount = amount - quantity; inventory.setInventory(amount); try { em.merge(inventory); } catch (OptimisticLockException e) { return -9999; } return quantity; } else { inventory.setInventory(0); try { em.merge(inventory); } catch (OptimisticLockException e) { return -9999; } return amount; } } else { return amount; } }
@Override public void addTrend(String name, Kwet kwet) { Query q = em.createQuery("select trend from Trends trend where trend.name = :name "); q.setParameter("name", name); List<Trend> trends = q.getResultList(); Trend trend = null; if (trends.isEmpty()) { trend = new Trend(name); em.persist(trend); trend.addKwet(kwet); kwet.addTrend(trend); em.merge(trend); em.merge(kwet); } else { trend = trends.get(0); if (!trend.getKwets().contains(kwet)) { trend.addKwet(kwet); kwet.addTrend(trend); em.merge(trend); em.merge(kwet); } } }
public void destroy(long id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); CheckoutRecord checkoutRecord; try { checkoutRecord = em.getReference(CheckoutRecord.class, id); checkoutRecord.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The checkoutRecord with id " + id + " no longer exists.", enfe); } Member member = checkoutRecord.getMember(); if (member != null) { member.getRecords().remove(checkoutRecord); member = em.merge(member); } Fine fine = checkoutRecord.getFine(); if (fine != null) { fine.setRecord(null); fine = em.merge(fine); } em.remove(checkoutRecord); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Tema tema; try { tema = em.getReference(Tema.class, id); tema.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The tema with id " + id + " no longer exists.", enfe); } Clase idAreaDerecho = tema.getIdAreaDerecho(); if (idAreaDerecho != null) { idAreaDerecho.getTemaList().remove(tema); idAreaDerecho = em.merge(idAreaDerecho); } List<Normatividad> normatividadList = tema.getNormatividadList(); for (Normatividad normatividadListNormatividad : normatividadList) { normatividadListNormatividad.setIdTema(null); normatividadListNormatividad = em.merge(normatividadListNormatividad); } List<Proceso> procesoList = tema.getProcesoList(); for (Proceso procesoListProceso : procesoList) { procesoListProceso.setIdTema(null); procesoListProceso = em.merge(procesoListProceso); } em.remove(tema); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Inventary inventary; try { inventary = em.getReference(Inventary.class, id); inventary.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The inventary with id " + id + " no longer exists.", enfe); } Product productId = inventary.getProductId(); if (productId != null) { productId.getInventaryList().remove(inventary); productId = em.merge(productId); } Billing billingId = inventary.getBillingId(); if (billingId != null) { billingId.getInventaryList().remove(inventary); billingId = em.merge(billingId); } em.remove(inventary); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Livreurs livreurs; try { livreurs = em.getReference(Livreurs.class, id); livreurs.getIdLivreur(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The livreurs with id " + id + " no longer exists.", enfe); } Statuts statut = livreurs.getStatut(); if (statut != null) { statut.getLivreursList().remove(livreurs); statut = em.merge(statut); } List<Clients> clientsList = livreurs.getClientsList(); for (Clients clientsListClients : clientsList) { clientsListClients.setIdLivreur(null); clientsListClients = em.merge(clientsListClients); } em.remove(livreurs); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
private void btnOKActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnOKActionPerformed EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); TradeForm myTradeForm = em.merge(tradeForm); em.lock(myTradeForm, LockModeType.OPTIMISTIC); myTradeForm.setSubtext(txtZusatz.getText()); DosageForm dosageForm = em.merge((DosageForm) cmbForm.getSelectedItem()); em.lock(dosageForm, LockModeType.OPTIMISTIC); myTradeForm.setDosageForm(dosageForm); em.getTransaction().commit(); tradeForm = myTradeForm; } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } dispose(); } // GEN-LAST:event_btnOKActionPerformed
public void create(ChequesProveedores chequesProveedores) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Proveedores proveedoresidProveedores = chequesProveedores.getProveedoresidProveedores(); if (proveedoresidProveedores != null) { proveedoresidProveedores = em.getReference( proveedoresidProveedores.getClass(), proveedoresidProveedores.getIdProveedores()); chequesProveedores.setProveedoresidProveedores(proveedoresidProveedores); } Bancos bancosIdbancos = chequesProveedores.getBancosIdbancos(); if (bancosIdbancos != null) { bancosIdbancos = em.getReference(bancosIdbancos.getClass(), bancosIdbancos.getIdbancos()); chequesProveedores.setBancosIdbancos(bancosIdbancos); } em.persist(chequesProveedores); if (proveedoresidProveedores != null) { proveedoresidProveedores.getChequesProveedoresCollection().add(chequesProveedores); proveedoresidProveedores = em.merge(proveedoresidProveedores); } if (bancosIdbancos != null) { bancosIdbancos.getChequesProveedoresCollection().add(chequesProveedores); bancosIdbancos = em.merge(bancosIdbancos); } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); ChequesProveedores chequesProveedores; try { chequesProveedores = em.getReference(ChequesProveedores.class, id); chequesProveedores.getIdchequesProveedores(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The chequesProveedores with id " + id + " no longer exists.", enfe); } Proveedores proveedoresidProveedores = chequesProveedores.getProveedoresidProveedores(); if (proveedoresidProveedores != null) { proveedoresidProveedores.getChequesProveedoresCollection().remove(chequesProveedores); proveedoresidProveedores = em.merge(proveedoresidProveedores); } Bancos bancosIdbancos = chequesProveedores.getBancosIdbancos(); if (bancosIdbancos != null) { bancosIdbancos.getChequesProveedoresCollection().remove(chequesProveedores); bancosIdbancos = em.merge(bancosIdbancos); } em.remove(chequesProveedores); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
private MeasurementBaseline calculateBaselineForGroup( int groupId, int definitionId, boolean userEntered, long startDate, long endDate, boolean save) throws DataNotAvailableException, BaselineCreationException { MeasurementAggregate agg = dataManager.getAggregate( subjectManager.getOverlord(), groupId, definitionId, startDate, endDate); Subject overlord = subjectManager.getOverlord(); List<Integer> resourceIds = resourceManager.findImplicitResourceIdsByResourceGroup(groupId); List<MeasurementSchedule> schedules = measurementScheduleManager.findSchedulesByResourceIdsAndDefinitionId( overlord, ArrayUtils.unwrapCollection(resourceIds), definitionId); MeasurementBaseline baseline = null; for (MeasurementSchedule schedule : schedules) { // attach the entity, so we can find the baseline schedule = entityManager.merge(schedule); if (save && (schedule.getBaseline() != null)) { /* * If saving, make sure we're updating the existing one, if it exists */ baseline = schedule.getBaseline(); } else { /* * Otherwise, if we're not saving or if the the schedule doesn't have a current baseline, we create a new * baseline object */ baseline = new MeasurementBaseline(); if (save) { /* * But, if we *are* in save mode, then set the relationship so when we merge the schedule below it * persists this new baseline too */ baseline.setSchedule(schedule); } } baseline.setUserEntered(userEntered); baseline.setMean(agg.getAvg()); baseline.setMin(agg.getMin()); baseline.setMax(agg.getMax()); if (save) { entityManager.persist(baseline); entityManager.merge(schedule); } } // all baselines should be the same return baseline; }
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Produto produto; try { produto = em.getReference(Produto.class, id); produto.getIdproduto(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The produto with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; List<DetalheVenda> detalheVendaListOrphanCheck = produto.getDetalheVendaList(); for (DetalheVenda detalheVendaListOrphanCheckDetalheVenda : detalheVendaListOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "This Produto (" + produto + ") cannot be destroyed since the DetalheVenda " + detalheVendaListOrphanCheckDetalheVenda + " in its detalheVendaList field has a non-nullable produto field."); } List<Promocao> promocaoListOrphanCheck = produto.getPromocaoList(); for (Promocao promocaoListOrphanCheckPromocao : promocaoListOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "This Produto (" + produto + ") cannot be destroyed since the Promocao " + promocaoListOrphanCheckPromocao + " in its promocaoList field has a non-nullable codProduto field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Unidade codUnidade = produto.getCodUnidade(); if (codUnidade != null) { codUnidade.getProdutoList().remove(produto); codUnidade = em.merge(codUnidade); } Categoria codCategoria = produto.getCodCategoria(); if (codCategoria != null) { codCategoria.getProdutoList().remove(produto); codCategoria = em.merge(codCategoria); } em.remove(produto); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
@Test public void testMergeMultipleEntityCopiesAllowedAndDisallowed() { Item item1 = new Item(); item1.setName("item1 name"); Category category = new Category(); category.setName("category"); item1.setCategory(category); category.setExampleItem(item1); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist(item1); em.getTransaction().commit(); em.close(); // get another representation of item1 em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item1_1 = em.find(Item.class, item1.getId()); // make sure item1_1.category is initialized Hibernate.initialize(item1_1.getCategory()); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item1Merged = em.merge(item1); // make sure item1Merged.category is also managed Hibernate.initialize(item1Merged.getCategory()); item1Merged.setCategory(category); category.setExampleItem(item1_1); // now item1Merged is managed and it has a nested detached item // and there is multiple managed/detached Category objects try { // the following should fail because multiple copies of Category objects is not allowed by // CustomEntityCopyObserver em.merge(item1Merged); fail( "should have failed because CustomEntityCopyObserver does not allow multiple copies of a Category. "); } catch (IllegalStateException ex) { // expected } finally { em.getTransaction().rollback(); } em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); item1 = em.find(Item.class, item1.getId()); assertEquals(category.getName(), item1.getCategory().getName()); assertSame(item1, item1.getCategory().getExampleItem()); em.getTransaction().commit(); em.close(); cleanup(); }
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 edit(Groupe groupe) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Groupe persistentGroupe = em.find(Groupe.class, groupe.getIdgroupe()); Collection<Utilisateur> utilisateurCollectionOld = persistentGroupe.getUtilisateurCollection(); Collection<Utilisateur> utilisateurCollectionNew = groupe.getUtilisateurCollection(); Collection<Utilisateur> attachedUtilisateurCollectionNew = new ArrayList<Utilisateur>(); for (Utilisateur utilisateurCollectionNewUtilisateurToAttach : utilisateurCollectionNew) { utilisateurCollectionNewUtilisateurToAttach = em.getReference( utilisateurCollectionNewUtilisateurToAttach.getClass(), utilisateurCollectionNewUtilisateurToAttach.getIdutilisateur()); attachedUtilisateurCollectionNew.add(utilisateurCollectionNewUtilisateurToAttach); } utilisateurCollectionNew = attachedUtilisateurCollectionNew; groupe.setUtilisateurCollection(utilisateurCollectionNew); groupe = em.merge(groupe); for (Utilisateur utilisateurCollectionOldUtilisateur : utilisateurCollectionOld) { if (!utilisateurCollectionNew.contains(utilisateurCollectionOldUtilisateur)) { utilisateurCollectionOldUtilisateur.setIdgroupe(null); utilisateurCollectionOldUtilisateur = em.merge(utilisateurCollectionOldUtilisateur); } } for (Utilisateur utilisateurCollectionNewUtilisateur : utilisateurCollectionNew) { if (!utilisateurCollectionOld.contains(utilisateurCollectionNewUtilisateur)) { Groupe oldIdgroupeOfUtilisateurCollectionNewUtilisateur = utilisateurCollectionNewUtilisateur.getIdgroupe(); utilisateurCollectionNewUtilisateur.setIdgroupe(groupe); utilisateurCollectionNewUtilisateur = em.merge(utilisateurCollectionNewUtilisateur); if (oldIdgroupeOfUtilisateurCollectionNewUtilisateur != null && !oldIdgroupeOfUtilisateurCollectionNewUtilisateur.equals(groupe)) { oldIdgroupeOfUtilisateurCollectionNewUtilisateur .getUtilisateurCollection() .remove(utilisateurCollectionNewUtilisateur); oldIdgroupeOfUtilisateurCollectionNewUtilisateur = em.merge(oldIdgroupeOfUtilisateurCollectionNewUtilisateur); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = groupe.getIdgroupe(); if (findGroupe(id) == null) { throw new NonexistentEntityException("The groupe with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); // em.getTransaction().begin(); Dir dir; try { dir = em.getReference(Dir.class, id); dir.getDirID(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The dir with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; List<SVNVersion> SVNVersionListOrphanCheck = dir.getSVNVersionList(); for (SVNVersion SVNVersionListOrphanCheckSVNVersion : SVNVersionListOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "This Dir (" + dir + ") cannot be destroyed since the SVNVersion " + SVNVersionListOrphanCheckSVNVersion + " in its SVNVersionList field has a non-nullable dir field."); } List<SVNFile> SVNFileListOrphanCheck = dir.getSVNFileList(); for (SVNFile SVNFileListOrphanCheckSVNFile : SVNFileListOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "This Dir (" + dir + ") cannot be destroyed since the SVNFile " + SVNFileListOrphanCheckSVNFile + " in its SVNFileList field has a non-nullable dir field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } SVNRepo SVNRepo = dir.getSVNRepo(); if (SVNRepo != null) { SVNRepo.getDirList().remove(dir); SVNRepo = em.merge(SVNRepo); } Revision revision = dir.getRevision(); if (revision != null) { revision.getDirList().remove(dir); revision = em.merge(revision); } em.remove(dir); // em.getTransaction().commit(); } finally { if (em != null) { // em.close(); } } }
public void edit(Tipousuario tipousuario) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Tipousuario persistentTipousuario = em.find(Tipousuario.class, tipousuario.getTipUsuCod()); Collection<Usuario> usuarioCollectionOld = persistentTipousuario.getUsuarioCollection(); Collection<Usuario> usuarioCollectionNew = tipousuario.getUsuarioCollection(); Collection<Usuario> attachedUsuarioCollectionNew = new ArrayList<Usuario>(); for (Usuario usuarioCollectionNewUsuarioToAttach : usuarioCollectionNew) { usuarioCollectionNewUsuarioToAttach = em.getReference( usuarioCollectionNewUsuarioToAttach.getClass(), usuarioCollectionNewUsuarioToAttach.getUsuCod()); attachedUsuarioCollectionNew.add(usuarioCollectionNewUsuarioToAttach); } usuarioCollectionNew = attachedUsuarioCollectionNew; tipousuario.setUsuarioCollection(usuarioCollectionNew); tipousuario = em.merge(tipousuario); for (Usuario usuarioCollectionOldUsuario : usuarioCollectionOld) { if (!usuarioCollectionNew.contains(usuarioCollectionOldUsuario)) { usuarioCollectionOldUsuario.setTipUsuCod(null); usuarioCollectionOldUsuario = em.merge(usuarioCollectionOldUsuario); } } for (Usuario usuarioCollectionNewUsuario : usuarioCollectionNew) { if (!usuarioCollectionOld.contains(usuarioCollectionNewUsuario)) { Tipousuario oldTipUsuCodOfUsuarioCollectionNewUsuario = usuarioCollectionNewUsuario.getTipUsuCod(); usuarioCollectionNewUsuario.setTipUsuCod(tipousuario); usuarioCollectionNewUsuario = em.merge(usuarioCollectionNewUsuario); if (oldTipUsuCodOfUsuarioCollectionNewUsuario != null && !oldTipUsuCodOfUsuarioCollectionNewUsuario.equals(tipousuario)) { oldTipUsuCodOfUsuarioCollectionNewUsuario .getUsuarioCollection() .remove(usuarioCollectionNewUsuario); oldTipUsuCodOfUsuarioCollectionNewUsuario = em.merge(oldTipUsuCodOfUsuarioCollectionNewUsuario); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = tipousuario.getTipUsuCod(); if (findTipousuario(id) == null) { throw new NonexistentEntityException( "The tipousuario with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Empleado empleado; try { empleado = em.getReference(Empleado.class, id); empleado.getEmpDni(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The empleado with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; Collection<Usuario> usuarioCollectionOrphanCheck = empleado.getUsuarioCollection(); for (Usuario usuarioCollectionOrphanCheckUsuario : usuarioCollectionOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "This Empleado (" + empleado + ") cannot be destroyed since the Usuario " + usuarioCollectionOrphanCheckUsuario + " in its usuarioCollection field has a non-nullable empDni field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Turno turCod = empleado.getTurCod(); if (turCod != null) { turCod.getEmpleadoCollection().remove(empleado); turCod = em.merge(turCod); } Cargo carCod = empleado.getCarCod(); if (carCod != null) { carCod.getEmpleadoCollection().remove(empleado); carCod = em.merge(carCod); } Collection<Gastos> gastosCollection = empleado.getGastosCollection(); for (Gastos gastosCollectionGastos : gastosCollection) { gastosCollectionGastos.setEmpDni(null); gastosCollectionGastos = em.merge(gastosCollectionGastos); } Collection<RegistroFalta> registroFaltaCollection = empleado.getRegistroFaltaCollection(); for (RegistroFalta registroFaltaCollectionRegistroFalta : registroFaltaCollection) { registroFaltaCollectionRegistroFalta.setEmpDni(null); registroFaltaCollectionRegistroFalta = em.merge(registroFaltaCollectionRegistroFalta); } em.remove(empleado); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
public void edit(Carrera carrera) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Carrera persistentCarrera = em.find(Carrera.class, carrera.getIdCarrera()); Collection<Alumno> alumnoCollectionOld = persistentCarrera.getAlumnoCollection(); Collection<Alumno> alumnoCollectionNew = carrera.getAlumnoCollection(); Collection<Alumno> attachedAlumnoCollectionNew = new ArrayList<Alumno>(); for (Alumno alumnoCollectionNewAlumnoToAttach : alumnoCollectionNew) { alumnoCollectionNewAlumnoToAttach = em.getReference( alumnoCollectionNewAlumnoToAttach.getClass(), alumnoCollectionNewAlumnoToAttach.getIdAlumnos()); attachedAlumnoCollectionNew.add(alumnoCollectionNewAlumnoToAttach); } alumnoCollectionNew = attachedAlumnoCollectionNew; carrera.setAlumnoCollection(alumnoCollectionNew); carrera = em.merge(carrera); for (Alumno alumnoCollectionOldAlumno : alumnoCollectionOld) { if (!alumnoCollectionNew.contains(alumnoCollectionOldAlumno)) { alumnoCollectionOldAlumno.setIdCarreraFK(null); alumnoCollectionOldAlumno = em.merge(alumnoCollectionOldAlumno); } } for (Alumno alumnoCollectionNewAlumno : alumnoCollectionNew) { if (!alumnoCollectionOld.contains(alumnoCollectionNewAlumno)) { Carrera oldIdCarreraFKOfAlumnoCollectionNewAlumno = alumnoCollectionNewAlumno.getIdCarreraFK(); alumnoCollectionNewAlumno.setIdCarreraFK(carrera); alumnoCollectionNewAlumno = em.merge(alumnoCollectionNewAlumno); if (oldIdCarreraFKOfAlumnoCollectionNewAlumno != null && !oldIdCarreraFKOfAlumnoCollectionNewAlumno.equals(carrera)) { oldIdCarreraFKOfAlumnoCollectionNewAlumno .getAlumnoCollection() .remove(alumnoCollectionNewAlumno); oldIdCarreraFKOfAlumnoCollectionNewAlumno = em.merge(oldIdCarreraFKOfAlumnoCollectionNewAlumno); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = carrera.getIdCarrera(); if (findCarrera(id) == null) { throw new NonexistentEntityException("The carrera with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }