Example #1
1
 public void deleteNotValidatedUser(String _username) throws MSMApplicationException {
   NdgUser user = findNdgUserByName(_username);
   if (user != null) {
     try {
       // deleting transactionlog
       Query query = manager.createNamedQuery("transactionlog.findByUser");
       query.setParameter("_user", user);
       Transactionlog t = (Transactionlog) query.getSingleResult();
       manager.remove(t);
       // deleting surveys
       query = manager.createNamedQuery("survey.findByUser");
       query.setParameter("_user", user);
       ArrayList<Survey> surveysListDB = (ArrayList<Survey>) query.getResultList();
       for (Survey survey : surveysListDB) {
         manager.remove(survey);
       }
       // deleting user
       manager.remove(user);
     } catch (NoResultException e) {
       System.err.println(e.getMessage());
     }
   } else {
     throw new UserNotFoundException();
   }
 }
  public void delete(long pk) {
    List<LetterItem> itemList =
        (List<LetterItem>) em.createQuery(QUERY_ITEM_BY_ID).setParameter(ID, pk).getResultList();
    for (LetterItem item : itemList) {
      em.remove(item);
    }

    List<LetterText> textList =
        (List<LetterText>) em.createQuery(QUERY_TEXT_BY_ID).setParameter(ID, pk).getResultList();

    for (LetterText txt : textList) {
      em.remove(txt);
    }

    List<LetterDate> dateList =
        (List<LetterDate>) em.createQuery(QUERY_DATE_BY_ID).setParameter(ID, pk).getResultList();

    for (LetterDate date : dateList) {
      em.remove(date);
    }

    LetterModule delete =
        (LetterModule) em.createQuery(QUERY_LETTER_BY_ID).setParameter(ID, pk).getSingleResult();
    em.remove(delete);
  }
  @Test
  public void testCfgXmlPar() throws Exception {
    File testPackage = buildCfgXmlPar();
    addPackageToClasspath(testPackage);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cfgxmlpar", new HashMap());
    EntityManager em = emf.createEntityManager();
    Item i = new Item();
    i.setDescr("Blah");
    i.setName("factory");
    Morito m = new Morito();
    m.setPower("SuperStrong");
    em.getTransaction().begin();
    em.persist(i);
    em.persist(m);
    em.getTransaction().commit();

    em.getTransaction().begin();
    i = em.find(Item.class, i.getName());
    em.remove(i);
    em.remove(em.find(Morito.class, m.getId()));
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
 @Test
 public void testFindRemoved() {
   final JPAEnvironment env = getEnvironment();
   final EntityManager em = env.getEntityManager();
   try {
     env.beginTransaction(em);
     Island island = new Island();
     em.persist(island);
     env.commitTransactionAndClear(em);
     Integer islandId = Integer.valueOf(island.getId());
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     verify(
         em.find(Island.class, islandId) == null, "entity in state FOR_DELETE but found by find");
     env.rollbackTransactionAndClear(em);
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     em.flush();
     verify(
         em.find(Island.class, islandId) == null,
         "entity in state DELETE_EXECUTED but found by find");
     env.rollbackTransactionAndClear(em);
   } finally {
     closeEntityManager(em);
   }
 }
  @Test
  public void testDefaultPar() throws Exception {
    File testPackage = buildDefaultPar();
    addPackageToClasspath(testPackage);

    // run the test
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultpar", new HashMap());
    EntityManager em = emf.createEntityManager();
    ApplicationServer as = new ApplicationServer();
    as.setName("JBoss AS");
    Version v = new Version();
    v.setMajor(4);
    v.setMinor(0);
    v.setMicro(3);
    as.setVersion(v);
    Mouse mouse = new Mouse();
    mouse.setName("mickey");
    em.getTransaction().begin();
    em.persist(as);
    em.persist(mouse);
    assertEquals(1, em.createNamedQuery("allMouse").getResultList().size());
    Lighter lighter = new Lighter();
    lighter.name = "main";
    lighter.power = " 250 W";
    em.persist(lighter);
    em.flush();
    em.remove(lighter);
    em.remove(mouse);
    assertNotNull(as.getId());
    em.remove(as);
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
Example #6
0
  public void removeMediaart(MediaartDto mediaartDto, TheClientDto theClientDto)
      throws EJBExceptionLP {
    checkMediaartDto(mediaartDto);

    try {
      Query query = em.createNamedQuery("MediaartsprfindByMediaartCNr");
      query.setParameter(1, mediaartDto.getCNr());
      Collection<?> cl = query.getResultList();
      Mediaart mediaart = em.find(Mediaart.class, mediaartDto.getCNr());
      if (mediaart == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, "");
      }
      // Erst alle SPRs dazu loeschen.
      for (Iterator<?> iter = cl.iterator(); iter.hasNext(); ) {
        Mediaartspr item = (Mediaartspr) iter.next();
        em.remove(item);
      }

      em.remove(mediaart);
      em.flush();
      // }
      // catch (FinderException ex) {
      // throw new
      // EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, ex);
    } catch (EntityExistsException ex) {
      throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEIM_LOESCHEN, ex);
    }
  }
  @Test
  public void testJPAPolymorphicCollection() throws Exception {
    em.getTransaction().begin();
    Hero h = new Hero();
    h.setName("Spartacus");
    em.persist(h);
    SuperHero sh = new SuperHero();
    sh.setName("Batman");
    sh.setSpecialPower("Technology and samurai techniques");
    em.persist(sh);
    HeroClub hc = new HeroClub();
    hc.setName("My hero club");
    hc.getMembers().add(h);
    hc.getMembers().add(sh);
    em.persist(hc);
    em.getTransaction().commit();

    em.clear();

    em.getTransaction().begin();
    HeroClub lhc = em.find(HeroClub.class, hc.getName());
    assertThat(lhc).isNotNull();
    Hero lh = lhc.getMembers().get(0);
    assertThat(lh).isNotNull();
    assertThat(lh).isInstanceOf(Hero.class);
    Hero lsh = lhc.getMembers().get(1);
    assertThat(lsh).isNotNull();
    assertThat(lsh).isInstanceOf(SuperHero.class);
    lhc.getMembers().clear();
    em.remove(lh);
    em.remove(lsh);
    em.remove(lhc);
    em.getTransaction().commit();
  }
  @Test
  public void mapAndElementCollection() throws Exception {

    OneToManyAddress home = new OneToManyAddress();
    home.setCity("Paris");

    OneToManyAddress work = new OneToManyAddress();
    work.setCity("San Francisco");

    OneToManyUser user = new OneToManyUser();
    user.getAddresses().put("home", home);
    user.getAddresses().put("work", work);
    user.getNicknames().add("idrA");
    user.getNicknames().add("day[9]");

    em.persist(home);
    em.persist(work);
    em.persist(user);

    OneToManyUser user2 = new OneToManyUser();
    user2.getNicknames().add("idrA");
    user2.getNicknames().add("day[9]");

    em.persist(user2);
    em.flush();
    em.clear();

    user = em.find(OneToManyUser.class, user.getId());

    assertThat(user.getNicknames()).as("Should have 2 nick1").hasSize(2);
    assertThat(user.getNicknames()).as("Should contain nicks").contains("idrA", "day[9]");

    user.getNicknames().remove("idrA");
    user.getAddresses().remove("work");

    em.persist(user);
    em.flush();
    em.clear();

    user = em.find(OneToManyUser.class, user.getId());

    // TODO do null value
    assertThat(user.getAddresses()).as("List should have 1 elements").hasSize(1);
    assertThat(user.getAddresses().get("home").getCity())
        .as("home address should be under home")
        .isEqualTo(home.getCity());
    assertThat(user.getNicknames()).as("Should have 1 nick1").hasSize(1);
    assertThat(user.getNicknames()).as("Should contain nick").contains("day[9]");

    em.remove(user);
    // CascadeType.ALL 로 user 삭제 시 address 삭제 됨
    // em.srem(em.load(Address.class, home.getId()));
    // em.srem(em.load(Address.class, work.getId()));

    user2 = em.find(OneToManyUser.class, user2.getId());
    assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2);
    assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]");
    em.remove(user2);
    em.flush();
  }
  @SuppressWarnings({"unchecked"})
  private void cleanup() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();

    for (Hoarder hoarder : (List<Hoarder>) em.createQuery("from Hoarder").getResultList()) {
      hoarder.getItems().clear();
      em.remove(hoarder);
    }

    for (Category category : (List<Category>) em.createQuery("from Category").getResultList()) {
      if (category.getExampleItem() != null) {
        category.setExampleItem(null);
        em.remove(category);
      }
    }

    for (Item item : (List<Item>) em.createQuery("from Item").getResultList()) {
      item.setCategory(null);
      em.remove(item);
    }

    em.createQuery("delete from Item").executeUpdate();

    em.getTransaction().commit();
    em.close();
  }
  @Test
  public void testSequenceIdGenerationInJTA() throws Exception {
    getTransactionManager().begin();
    final EntityManager em = getFactory().createEntityManager();
    Song firstSong = new Song();
    firstSong.setSinger("Charlotte Church");
    firstSong.setTitle("Ave Maria");
    em.persist(firstSong);

    Song secondSong = new Song();
    secondSong.setSinger("Charlotte Church");
    secondSong.setTitle("Flower Duet");
    em.persist(secondSong);

    Actor firstActor = new Actor();
    firstActor.setName("Russell Crowe");
    firstActor.setBestMovieTitle("Gladiator");
    em.persist(firstActor);

    Actor secondActor = new Actor();
    secondActor.setName("Johnny Depp");
    secondActor.setBestMovieTitle("Pirates of the Caribbean");
    em.persist(secondActor);
    getTransactionManager().commit();

    em.clear();

    getTransactionManager().begin();
    firstSong = em.find(Song.class, firstSong.getId());
    assertThat(firstSong).isNotNull();
    assertThat(firstSong.getId()).isEqualTo(Song.INITIAL_VALUE);
    assertThat(firstSong.getTitle()).isEqualTo("Ave Maria");
    em.remove(firstSong);

    secondSong = em.find(Song.class, secondSong.getId());
    assertThat(secondSong).isNotNull();
    assertThat(secondSong.getId()).isEqualTo(Song.INITIAL_VALUE + 1);
    assertThat(secondSong.getTitle()).isEqualTo("Flower Duet");
    em.remove(secondSong);

    firstActor = em.find(Actor.class, firstActor.getId());
    assertThat(firstActor).isNotNull();
    assertThat(firstActor.getId()).isEqualTo(Actor.INITIAL_VALUE);
    assertThat(firstActor.getName()).isEqualTo("Russell Crowe");
    em.remove(firstActor);

    secondActor = em.find(Actor.class, secondActor.getId());
    assertThat(secondActor).isNotNull();
    assertThat(secondActor.getId()).isEqualTo(Actor.INITIAL_VALUE + 1);
    assertThat(secondActor.getName()).isEqualTo("Johnny Depp");
    em.remove(secondActor);
    getTransactionManager().commit();

    em.close();
  }
Example #11
0
  public void remove(BaseEntity instance) {
    if (em.contains(instance)) {
      em.remove(instance);
    } else {
      BaseEntity persistentInstance = em.find(instance.getClass(), instance.getId());

      if (persistentInstance != null) {
        em.remove(persistentInstance);
      }
    }
  }
 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 public void deleteGamePlatform(int id) {
   GamePlatform gamePlatform = entityManager.find(GamePlatform.class, id);
   if (gamePlatform != null) {
     List<Game> games = getGamesByGamePlatformId(id);
     for (int i = 0; i < games.size(); i++) {
       entityManager.remove(games.get(i));
     }
     entityManager.remove(gamePlatform);
   }
 }
 @Override
 public void delete(ServiceType entity) {
   try {
     if (em.contains(entity)) {
       em.remove(entity);
     } else {
       em.remove(em.merge(entity));
     }
   } catch (Exception e) {
     throw new Error(e.getLocalizedMessage());
   }
 }
Example #14
0
 /**
  * Remove the 'UserRole' entity
  *
  * @param entity 'UserRole' entity that going to remove
  */
 @Transactional
 public void remove(UserRole entity) {
   if (entityManager.contains(entity)) {
     entityManager.remove(entity);
   } else {
     System.out.println("UserRole: Remove : Searching for " + entity.toString());
     UserRole attached = entityManager.find(UserRole.class, entity.getUsroId());
     System.out.println("UserRole: Remove : Found " + attached.toString());
     entityManager.remove(attached);
   }
   entityManager.flush();
 }
Example #15
0
  // Update roles and protocolMappers to given consentEntity from the consentModel
  private void updateGrantedConsentEntity(
      UserConsentEntity consentEntity, UserConsentModel consentModel) {
    Collection<UserConsentProtocolMapperEntity> grantedProtocolMapperEntities =
        consentEntity.getGrantedProtocolMappers();
    Collection<UserConsentProtocolMapperEntity> mappersToRemove =
        new HashSet<UserConsentProtocolMapperEntity>(grantedProtocolMapperEntities);

    for (ProtocolMapperModel protocolMapper : consentModel.getGrantedProtocolMappers()) {
      UserConsentProtocolMapperEntity grantedProtocolMapperEntity =
          new UserConsentProtocolMapperEntity();
      grantedProtocolMapperEntity.setUserConsent(consentEntity);
      grantedProtocolMapperEntity.setProtocolMapperId(protocolMapper.getId());

      // Check if it's already there
      if (!grantedProtocolMapperEntities.contains(grantedProtocolMapperEntity)) {
        em.persist(grantedProtocolMapperEntity);
        em.flush();
        grantedProtocolMapperEntities.add(grantedProtocolMapperEntity);
      } else {
        mappersToRemove.remove(grantedProtocolMapperEntity);
      }
    }
    // Those mappers were no longer on consentModel and will be removed
    for (UserConsentProtocolMapperEntity toRemove : mappersToRemove) {
      grantedProtocolMapperEntities.remove(toRemove);
      em.remove(toRemove);
    }

    Collection<UserConsentRoleEntity> grantedRoleEntities = consentEntity.getGrantedRoles();
    Set<UserConsentRoleEntity> rolesToRemove =
        new HashSet<UserConsentRoleEntity>(grantedRoleEntities);
    for (RoleModel role : consentModel.getGrantedRoles()) {
      UserConsentRoleEntity consentRoleEntity = new UserConsentRoleEntity();
      consentRoleEntity.setUserConsent(consentEntity);
      consentRoleEntity.setRoleId(role.getId());

      // Check if it's already there
      if (!grantedRoleEntities.contains(consentRoleEntity)) {
        em.persist(consentRoleEntity);
        em.flush();
        grantedRoleEntities.add(consentRoleEntity);
      } else {
        rolesToRemove.remove(consentRoleEntity);
      }
    }
    // Those roles were no longer on consentModel and will be removed
    for (UserConsentRoleEntity toRemove : rolesToRemove) {
      grantedRoleEntities.remove(toRemove);
      em.remove(toRemove);
    }

    em.flush();
  }
  @Test
  public void testConfiguration() throws Exception {
    File testPackage = buildExplicitPar();
    addPackageToClasspath(testPackage);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1", new HashMap());
    Item item = new Item("Mouse", "Micro$oft mouse");
    Distributor res = new Distributor();
    res.setName("Bruce");
    item.setDistributors(new HashSet<Distributor>());
    item.getDistributors().add(res);
    Statistics stats = ((HibernateEntityManagerFactory) emf).getSessionFactory().getStatistics();
    stats.clear();
    stats.setStatisticsEnabled(true);

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();

    em.persist(res);
    em.persist(item);
    assertTrue(em.contains(item));

    em.getTransaction().commit();
    em.close();

    assertEquals(1, stats.getSecondLevelCachePutCount());
    assertEquals(0, stats.getSecondLevelCacheHitCount());

    em = emf.createEntityManager();
    em.getTransaction().begin();
    Item second = em.find(Item.class, item.getName());
    assertEquals(1, second.getDistributors().size());
    assertEquals(1, stats.getSecondLevelCacheHitCount());
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    second = em.find(Item.class, item.getName());
    assertEquals(1, second.getDistributors().size());
    assertEquals(3, stats.getSecondLevelCacheHitCount());
    for (Distributor distro : second.getDistributors()) {
      em.remove(distro);
    }
    em.remove(second);
    em.getTransaction().commit();
    em.close();

    stats.clear();
    stats.setStatisticsEnabled(false);
    emf.close();
  }
Example #17
0
  public boolean delete(Object key) {
    if (!isValidKeyType(key)) {
      return false;
    }

    EntityManager em = emf.createEntityManager();
    try {
      long entityFindBegin = timeService.time();
      Object entity = em.find(configuration.entityClass(), key);
      stats.addEntityFind(timeService.time() - entityFindBegin);
      if (entity == null) {
        return false;
      }
      MetadataEntity metadata = null;
      if (configuration.storeMetadata()) {
        byte[] keyBytes;
        try {
          keyBytes = marshaller.objectToByteBuffer(key);
        } catch (Exception e) {
          throw new JpaStoreException("Failed to marshall key", e);
        }
        long metadataFindBegin = timeService.time();
        metadata = em.find(MetadataEntity.class, keyBytes);
        stats.addMetadataFind(timeService.time() - metadataFindBegin);
      }

      EntityTransaction txn = em.getTransaction();
      if (trace) log.trace("Removing " + entity + "(" + toString(metadata) + ")");
      long txnBegin = timeService.time();
      txn.begin();
      try {
        long entityRemoveBegin = timeService.time();
        em.remove(entity);
        stats.addEntityRemove(timeService.time() - entityRemoveBegin);
        if (metadata != null) {
          long metadataRemoveBegin = timeService.time();
          em.remove(metadata);
          stats.addMetadataRemove(timeService.time() - metadataRemoveBegin);
        }
        txn.commit();
        stats.addRemoveTxCommitted(timeService.time() - txnBegin);
        return true;
      } catch (Exception e) {
        stats.addRemoveTxFailed(timeService.time() - txnBegin);
        throw new JpaStoreException("Exception caught in delete()", e);
      } finally {
        if (txn != null && txn.isActive()) txn.rollback();
      }
    } finally {
      em.close();
    }
  }
Example #18
0
 @Override
 public void deleteUnassginedFlights(List<FlightEntity> flightsUnassigned) {
   for (FlightEntity f : flightsUnassigned) {
     FlightEntity fD = em.find(FlightEntity.class, f.getId());
     if (fD != null) {
       FlightEntity fRD = em.find(FlightEntity.class, fD.getReverseFlight().getId());
       fD.setReverseFlight(null);
       fRD.setReverseFlight(null);
       em.remove(fD);
       em.remove(fRD);
     }
   }
 }
Example #19
0
  @BeforeClass(dependsOnMethods = "init")
  public void initData() {
    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    BasicTestEntity2 bte1 = new BasicTestEntity2("x", "a");
    BasicTestEntity2 bte2 = new BasicTestEntity2("y", "b");
    BasicTestEntity2 bte3 = new BasicTestEntity2("z", "c");
    em.persist(bte1);
    em.persist(bte2);
    em.persist(bte3);

    em.getTransaction().commit();

    // Revision 2
    em = getEntityManager();
    em.getTransaction().begin();

    bte1 = em.find(BasicTestEntity2.class, bte1.getId());
    bte2 = em.find(BasicTestEntity2.class, bte2.getId());
    bte3 = em.find(BasicTestEntity2.class, bte3.getId());
    bte1.setStr1("x2");
    bte2.setStr2("b2");
    em.remove(bte3);

    em.getTransaction().commit();

    // Revision 3
    em = getEntityManager();
    em.getTransaction().begin();

    bte2 = em.find(BasicTestEntity2.class, bte2.getId());
    em.remove(bte2);

    em.getTransaction().commit();

    // Revision 4
    em = getEntityManager();
    em.getTransaction().begin();

    bte1 = em.find(BasicTestEntity2.class, bte1.getId());
    em.remove(bte1);

    em.getTransaction().commit();

    id1 = bte1.getId();
    id2 = bte2.getId();
    id3 = bte3.getId();
  }
  @Override
  public boolean deleteUser(Long userId) {

    User user = entityManager.find(User.class, userId);
    entityManager.remove(user);
    return true;
  }
 @Override
 public void remove(Album album) throws IllegalArgumentException {
   if (album == null) {
     throw new IllegalArgumentException("Attempted to delete null entity.");
   }
   em.remove(findById(album.getId()));
 }
 /**
  * Deletes the authorization after removing it from any groups that might be referring to it
  *
  * @param em the entity manager reference
  * @param id the ID for authorizatino entity
  * @throws PersistenceException if there were any errors deleting the authorization
  */
 static void deleteAuthorization(EntityManager em, long id) throws PersistenceException {
   Authorization auth = em.find(Authorization.class, id);
   // may return null, if this entity is not saved, in which
   // case don't do anything.
   if (auth == null) {
     return;
   }
   // Iterate through all groups and remove the authorization from them
   Set<SummaryGroup> groups = auth.getGroups();
   if (groups != null) {
     for (SummaryGroup g : groups) {
       Group group = new SingleGroupQuery(g.getId()).fetch();
       Set<Authorization> auths = group.getAuthorizations();
       HashSet<Authorization> updated = new HashSet<Authorization>();
       for (Authorization a : auths) {
         if (a.getId() != auth.getId()) {
           updated.add(a);
         }
       }
       group.setAuthorizations(updated);
       group.save();
     }
   }
   em.remove(em.getReference(Authorization.class, auth.getId()));
 }
 @Override
 public void removeServiceData(Integer id) {
   ServiceData sd = findById(id);
   if (sd != null) {
     entityManager.remove(sd);
   }
 }
  /**
   * Deletes all Results and ResultSets of a test, selftest or survey
   *
   * @param olatRes
   * @param olatResDet
   * @param repRef
   * @return deleted ResultSets
   */
  public int deleteAllResults(Long olatRes, String olatResDet, Long repRef) {
    StringBuilder sb = new StringBuilder();
    sb.append("select rset from ").append(QTIResultSet.class.getName()).append(" as rset ");
    sb.append(
        " where rset.olatResource=:resId and rset.olatResourceDetail=:resSubPath and rset.repositoryRef=:repoKey ");

    EntityManager em = dbInstance.getCurrentEntityManager();
    List<QTIResultSet> sets =
        em.createQuery(sb.toString(), QTIResultSet.class)
            .setParameter("resId", olatRes)
            .setParameter("resSubPath", olatResDet)
            .setParameter("repoKey", repRef)
            .getResultList();

    StringBuilder delSb = new StringBuilder();
    delSb
        .append("delete from ")
        .append(QTIResult.class.getName())
        .append(" as res where res.resultSet.key=:setKey");
    Query delResults = em.createQuery(delSb.toString());
    for (QTIResultSet set : sets) {
      delResults.setParameter("setKey", set.getKey()).executeUpdate();
      em.remove(set);
    }
    return sets.size();
  }
 public void destroy(Integer id) throws NonexistentEntityException {
   EntityManager em = null;
   try {
     em = getEntityManager();
     em.getTransaction().begin();
     BarEntity bar;
     try {
       bar = em.getReference(BarEntity.class, id);
       bar.getId();
     } catch (EntityNotFoundException enfe) {
       throw new NonexistentEntityException("The bar with id " + id + " no longer exists.", enfe);
     }
     ContractEntity contract = bar.getContract();
     if (contract != null) {
       contract.getBarCollection().remove(bar);
       contract = em.merge(contract);
     }
     em.remove(bar);
     em.getTransaction().commit();
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
  @Override
  public void delete(User obj) {

    em.getTransaction().begin();
    em.remove(obj);
    em.getTransaction().commit();
  }
 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();
     }
   }
 }
Example #28
0
 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();
     }
   }
 }
  @Test
  public void testExcludeHbmPar() throws Exception {
    File testPackage = buildExcludeHbmPar();
    addPackageToClasspath(testPackage);

    EntityManagerFactory emf = null;
    try {
      emf = Persistence.createEntityManagerFactory("excludehbmpar", new HashMap());
    } catch (PersistenceException e) {
      Throwable nested = e.getCause();
      if (nested == null) {
        throw e;
      }
      nested = nested.getCause();
      if (nested == null) {
        throw e;
      }
      if (!(nested instanceof ClassNotFoundException)) {
        throw e;
      }
      fail("Try to process hbm file: " + e.getMessage());
    }
    EntityManager em = emf.createEntityManager();
    Caipirinha s = new Caipirinha("Strong");
    em.getTransaction().begin();
    em.persist(s);
    em.getTransaction().commit();

    em.getTransaction().begin();
    s = em.find(Caipirinha.class, s.getId());
    em.remove(s);
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
Example #30
-1
  public String eliminarConyugue(String ideGtemp) {
    EntityManager manejador = fabrica.createEntityManager();
    try {
      GthConyuge conygue = getConyuque(ideGtemp);
      if (conygue != null) {
        utx.begin();
        manejador.joinTransaction();
        // Borra telefono de conyugue
        List<GthTelefono> telefonos = getListaTelefonoConyugue(conygue.getIdeGtcon().toString());
        if (telefonos != null && !telefonos.isEmpty()) {
          for (GthTelefono telefonoActual : telefonos) {
            manejador.remove(telefonoActual);
          }
        }
        // Borra datos de union
        GthUnionLibre union = getUnionLibre(conygue.getIdeGtcon().toString());
        if (union != null) {
          manejador.remove(union);
        }
        manejador.remove(conygue);
        utx.commit();
      }

    } catch (Exception e) {
      try {
        utx.rollback();
      } catch (Exception e1) {
      }
      return e.getMessage();
    } finally {
      manejador.close();
    }
    return "";
  }