public void create(Usuario usuario) throws PreexistingEntityException, Exception {
   EntityManager em = null;
   try {
     em = getEntityManager();
     em.getTransaction().begin();
     Investigador investigadorIdentificacion = usuario.getInvestigadorIdentificacion();
     if (investigadorIdentificacion != null) {
       investigadorIdentificacion =
           em.getReference(
               investigadorIdentificacion.getClass(),
               investigadorIdentificacion.getIdentificacion());
       usuario.setInvestigadorIdentificacion(investigadorIdentificacion);
     }
     em.persist(usuario);
     if (investigadorIdentificacion != null) {
       investigadorIdentificacion.getUsuarioList().add(usuario);
       investigadorIdentificacion = em.merge(investigadorIdentificacion);
     }
     em.getTransaction().commit();
   } catch (Exception ex) {
     if (findUsuario(usuario.getNombre()) != null) {
       throw new PreexistingEntityException("Usuario " + usuario + " already exists.", ex);
     }
     throw ex;
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
 public PurchaseDTO getPurchase(Long id) {
   entityManager.getTransaction().begin();
   PurchaseDTO result =
       PurchaseConverter.entity2PersistenceDTO(entityManager.find(PurchaseEntity.class, id));
   entityManager.getTransaction().commit();
   return result;
 }
 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();
     }
   }
 }
Example #4
0
 public static Project createProject(Project project) {
   EntityManager em = getEM();
   em.getTransaction().begin();
   em.persist(project);
   em.getTransaction().commit();
   return project;
 }
Example #5
0
 public static void assignUserToProject(Long projectID, Long userID) {
   EntityManager em = getEM();
   ProjectUser pu = em.find(ProjectUser.class, userID);
   em.getTransaction().begin();
   pu.setContributor(em.find(Project.class, projectID));
   em.getTransaction().commit();
 }
  public void executeEscalatedDeadline(
      Task task, Deadline deadline, EntityManager em, TaskService service) {
    if (deadline == null || deadline.getEscalations() == null) {
      return;
    }

    for (Escalation escalation : deadline.getEscalations()) {
      // we won't impl constraints for now
      // escalation.getConstraints()
      String language = "es_CL";
      for (Notification notification : escalation.getNotifications()) {
        if (notification.getNotificationType() == NotificationType.Email) {
          executeEmailNotification((EmailNotification) notification, task, em);
        }
      }

      if (!escalation.getReassignments().isEmpty()) {
        // get first and ignore the rest.
        Reassignment reassignment = escalation.getReassignments().get(0);
        em.getTransaction().begin();
        task.getTaskData().setStatus(Status.Ready);
        List potentialOwners = new ArrayList(reassignment.getPotentialOwners());
        task.getPeopleAssignments().setPotentialOwners(potentialOwners);
        em.getTransaction().commit();
      }
    }
    em.getTransaction().begin();
    deadline.setEscalated(true);
    em.getTransaction().commit();
  }
Example #7
0
 @Override
 public T add(T entry) {
   em.getTransaction().begin();
   T newEntry = em.merge(entry);
   em.getTransaction().commit();
   return newEntry;
 }
  @Test
  @Priority(10)
  public void initData() {
    EntityManager em = getEntityManager();

    SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1");

    SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1");

    // Revision 1
    em.getTransaction().begin();

    em.persist(ed1);

    em.getTransaction().commit();

    // Revision 2

    em.getTransaction().begin();

    ed1 = em.find(SetRefEdEntity.class, ed1.getId());

    em.persist(ing1);

    ed1.setReffering(new HashSet<SetRefIngEntity>());
    ed1.getReffering().add(ing1);

    em.getTransaction().commit();

    //

    ed1_id = ed1.getId();

    ing1_id = ing1.getId();
  }
  @Test
  @Priority(10)
  public void initData() throws InterruptedException {
    timestamp1 = System.currentTimeMillis();

    Thread.sleep(100);

    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    StrTestEntity te = new StrTestEntity("x");
    em.persist(te);
    id = te.getId();
    em.getTransaction().commit();

    timestamp2 = System.currentTimeMillis();

    Thread.sleep(100);

    // Revision 2
    em.getTransaction().begin();
    te = em.find(StrTestEntity.class, id);
    te.setStr("y");
    em.getTransaction().commit();

    timestamp3 = System.currentTimeMillis();
  }
  @Override
  public List<Event> getChildAdoptionRecords(Person person) {
    // get the birth records of the children of this parent
    List<Adoption> adoptionRecords = new ArrayList<Adoption>();
    em.getTransaction().begin();
    TypedQuery<Adoption> q =
        em.createQuery(
            "select b from Adoption b, IN(b.parents) p WHERE p.id = :idParam", Adoption.class);
    q.setParameter("idParam", person.getId());

    adoptionRecords.addAll(q.getResultList());

    List<Event> adoptions = new ArrayList<Event>();
    for (Adoption b : adoptionRecords) {
      if (b != null) {
        AdoptedChildRecord cr = new AdoptedChildRecord();
        cr.setEventDate(b.getEventDate());
        cr.setPerson(person);
        cr.setChild(b.getPerson());
        cr.setTown(b.getTown());
        cr.setState_province(b.getState_province());
        cr.setCountry(b.getCountry());
        adoptions.add(cr);
      }
    }
    em.getTransaction().commit();
    return adoptions;
  }
  @SuppressWarnings("unchecked")
  @Override
  public Set<Person> getTopAncestors() {
    Set<Person> topAncestors = new HashSet<Person>();
    // Find all the parents
    // If a person is in the childrenmap as a key,
    // then they are registered as a parent to somebody
    em.getTransaction().begin();
    TypedQuery q = em.createQuery("select p.parents from Birth p", Person.class);
    List<Person> people = (List<Person>) q.getResultList();
    em.getTransaction().commit();

    for (Person person : people) {
      // If a person doesn't have a birth record,
      // then there's no record of a parent
      System.out.println("Found " + person);
      Birth birthRecord = findBirthRecord(person);
      if (birthRecord == null || birthRecord.getParents().isEmpty()) {
        System.out.println("Adding " + person + " to top ancestors list");
        topAncestors.add(person);
      }
    }

    return topAncestors;
  }
  @Override
  public List<Event> getChildrenBirths(Person person) {
    // get the birth records of the children of this parent
    List<Birth> birthRecords = new ArrayList<Birth>();
    em.getTransaction().begin();
    Query q = em.createQuery("select b from Birth b, IN(b.parents) p WHERE p.id = :idParam");
    q.setParameter("idParam", person.getId());

    birthRecords.addAll((Collection<? extends Birth>) q.getResultList());

    List<Event> childrenBirths = new ArrayList<Event>();
    for (Birth b : birthRecords) {
      if (b != null) {
        ChildRecord cr = new ChildRecord();
        cr.setEventDate(b.getEventDate());
        cr.setPerson(person);
        cr.setChild(b.getPerson());
        cr.setTown(b.getTown());
        cr.setState_province(b.getState_province());
        cr.setCountry(b.getCountry());
        childrenBirths.add(cr);
      }
    }
    em.getTransaction().commit();
    return childrenBirths;
  }
  @Override
  public Set<Person> getSiblingsAll(Person thisPerson) {
    // return full and half siblings of thisPerson
    // exclude thisPerson from the set

    Set<Person> siblings = new HashSet<Person>();
    List<Person> parents = new ArrayList<Person>();

    em.getTransaction().begin();
    Query q =
        em.createQuery(
            "select b.parents from Birth b, IN(b.person) p WHERE p.id = :personId"
                + " or p.id = :parent2Id");
    q.setParameter("personId", thisPerson.getId());

    parents.addAll((Collection<? extends Person>) q.getResultList());

    if (!parents.isEmpty()) {
      if (parents.size() == 2) {
        siblings = getChildrenAll(parents.get(0), parents.get(1));
      } else if (parents.size() == 1) {
        siblings = getChildren(parents.get(0));
      }
    }
    em.getTransaction().commit();
    siblings.remove(thisPerson);
    return siblings;
  }
Example #14
0
  /** Test of an SQL query using a result set mapping giving two entities (Login + LoginAccount). */
  public void testSQLResult() {
    if (vendorID == null) {
      return;
    }
    try {
      EntityManager em = getEM();
      EntityTransaction tx = em.getTransaction();
      try {
        tx.begin();

        LoginAccount acct = new LoginAccount(1, "Fred", "Flintstone");
        Login login = new Login("flintstone", "pwd");
        acct.setLogin(login);
        em.persist(login);
        em.persist(acct);

        tx.commit();
      } finally {
        if (tx.isActive()) {
          tx.rollback();
        }
        em.close();
      }

      em = getEM();
      tx = em.getTransaction();
      try {
        tx.begin();

        // Check the results
        List result =
            em.createNativeQuery(
                    "SELECT P.ID, P.FIRSTNAME, P.LASTNAME, P.LOGIN_ID, L.ID, L.USERNAME, L.PASSWORD "
                        + "FROM JPA_AN_LOGINACCOUNT P, JPA_AN_LOGIN L",
                    "AN_LOGIN_PLUS_ACCOUNT")
                .getResultList();
        assertEquals(1, result.size());

        Iterator iter = result.iterator();
        while (iter.hasNext()) {
          // Should be a String (type of "ID" column)
          Object[] obj = (Object[]) iter.next();
          assertEquals("Fred", ((LoginAccount) obj[0]).getFirstName());
          assertEquals("flintstone", ((Login) obj[1]).getUserName());
          assertEquals("Fred", ((LoginAccount) obj[0]).getFirstName());
          assertTrue(((LoginAccount) obj[0]).getLogin() == ((Login) obj[1]));
        }

        tx.rollback();
      } finally {
        if (tx.isActive()) {
          tx.rollback();
        }
        em.close();
      }
    } finally {
      clean(LoginAccount.class);
      clean(Login.class);
    }
  }
  @Override
  public void create(User obj) {

    em.getTransaction().begin();
    em.persist(obj);
    em.getTransaction().commit();
  }
  /**
   * Refresh method test loads an entity with two different entity managers. One updates the entity
   * and another refreshes it. The test checks whether refreshed entity contains changes.
   */
  @Test
  public void entityEquality_refresh_EntityManager() {
    // load an entity
    EntityManager emRefresh = factory.createEntityManager();
    Person person1 = emRefresh.find(Person.class, SIMON_SLASH_ID);

    // load the same entity by different entity manager
    EntityManager emChange = factory.createEntityManager();
    Person person2 = emChange.find(Person.class, SIMON_SLASH_ID);

    // change the first entity - second entity remains the same
    emRefresh.getTransaction().begin();
    person1.setFirstName("refreshDemo");
    assertNotSame("refreshDemo", person2.getFirstName());

    // commit the transaction - second entity still remains the same
    emRefresh.getTransaction().commit();
    assertNotSame("refreshDemo", person2.getFirstName());

    // refresh second entity - it changes
    emChange.refresh(person2);
    assertEquals("refreshDemo", person2.getFirstName());

    emRefresh.close();
    emChange.close();
  }
  @Override
  public void delete(User obj) {

    em.getTransaction().begin();
    em.remove(obj);
    em.getTransaction().commit();
  }
  @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();
  }
 public void addCurr(List<Currency> currency) {
   em.getTransaction().begin();
   for (Currency c : currency) {
     em.persist(c);
   }
   em.getTransaction().commit();
 }
  @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();
  }
Example #21
0
  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
  @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 #23
0
 public static ProjectUser createUser(ProjectUser user) {
   EntityManager em = getEM();
   em.getTransaction().begin();
   em.persist(user);
   em.getTransaction().commit();
   return user;
 }
Example #24
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();
     }
   }
 }
 public PurchaseDTO createPurchase(PurchaseDTO purchase) {
   PurchaseEntity entity = PurchaseConverter.persistenceDTO2Entity(purchase);
   entityManager.getTransaction().begin();
   entityManager.persist(entity);
   entityManager.getTransaction().commit();
   return PurchaseConverter.entity2PersistenceDTO(entity);
 }
 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 create(BarEntity bar) throws PreexistingEntityException, Exception {
   EntityManager em = null;
   try {
     em = getEntityManager();
     em.getTransaction().begin();
     ContractEntity contract = bar.getContract();
     if (contract != null) {
       contract = em.getReference(contract.getClass(), contract.getId());
       bar.setContract(contract);
     }
     em.persist(bar);
     if (contract != null) {
       contract.getBarCollection().add(bar);
       contract = em.merge(contract);
     }
     em.getTransaction().commit();
   } catch (Exception ex) {
     if (findBar(bar.getId()) != null) {
       throw new PreexistingEntityException("Bar " + bar + " already exists.", ex);
     }
     throw ex;
   } finally {
     if (em != null /*&& em.isOpen()*/) {
       em.close();
     }
   }
 }
 private void setH2LockTimeout() {
   EntityManager manager = entityManagerFactory.createEntityManager();
   manager.getTransaction().begin();
   manager.createNativeQuery("SET DEFAULT_LOCK_TIMEOUT " + locktimeout).executeUpdate();
   manager.getTransaction().commit();
   manager.close();
 }
  @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();
  }
 public void destroy(String id) throws NonexistentEntityException {
   EntityManager em = null;
   try {
     em = getEntityManager();
     em.getTransaction().begin();
     Usuario usuario;
     try {
       usuario = em.getReference(Usuario.class, id);
       usuario.getNombre();
     } catch (EntityNotFoundException enfe) {
       throw new NonexistentEntityException(
           "The usuario with id " + id + " no longer exists.", enfe);
     }
     Investigador investigadorIdentificacion = usuario.getInvestigadorIdentificacion();
     if (investigadorIdentificacion != null) {
       investigadorIdentificacion.getUsuarioList().remove(usuario);
       investigadorIdentificacion = em.merge(investigadorIdentificacion);
     }
     em.remove(usuario);
     em.getTransaction().commit();
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }