Ejemplo n.º 1
11
  public List<Company> retrieveCompanys(String name, String category) {
    EntityManager em = createEntityManager();
    List<Company> company = null;
    try {
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Company> cq = cb.createQuery(Company.class);
      Root<Company> c = cq.from(Company.class);
      List<Predicate> conditions = new ArrayList<Predicate>();
      if (name != null) {
        Predicate nameCondition = cb.like(c.get(Company_.name), "%" + name + "%");
        conditions.add(nameCondition);
      }
      if (category != null) {
        Path<CompanyCategory> companyCategoryPath = c.get(Company_.category);
        Path<String> companyCategoryNamePath =
            companyCategoryPath.get(CompanyCategory_.categoryName);
        Predicate categoryCondition = cb.like(companyCategoryNamePath, category + "%");
        conditions.add(categoryCondition);
      }
      cq.where(conditions.toArray(new Predicate[0]));
      TypedQuery<Company> query = em.createQuery(cq);
      company = query.getResultList();
    } finally {
      em.close();
    }

    return company;
  }
  @Test
  public void testArray() {
    EntityManager em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    Customer c1 = new Customer();
    c1.setId("c1");
    c1.setAge(18);
    c1.setName("Bob");
    em.persist(c1);
    em.getTransaction().commit();
    em.close();

    em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> q = cb.createQuery(Object[].class);
    Root<Customer> c = q.from(Customer.class);
    q.select(cb.array(c.get(Customer_.name), c.get(Customer_.age)));
    List<Object[]> result = em.createQuery(q).getResultList();
    assertEquals(1, result.size());
    assertEquals(c1.getName(), result.get(0)[0]);
    assertEquals(c1.getAge(), result.get(0)[1]);
    em.getTransaction().commit();
    em.close();

    em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete Customer").executeUpdate();
    em.getTransaction().commit();
    em.close();
  }
 public AppCatalogResource get(Object identifier) throws AppCatalogException {
   EntityManager em = null;
   try {
     em = AppCatalogJPAUtils.getEntityManager();
     em.getTransaction().begin();
     AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(GLOBUS_SUBMISSION);
     generator.setParameter(GlobusJobSubmissionConstants.SUBMISSION_ID, identifier);
     Query q = generator.selectQuery(em);
     GlobusJobSubmission globusJobSubmission = (GlobusJobSubmission) q.getSingleResult();
     GlobusJobSubmissionResource globusJobSubmissionResource =
         (GlobusJobSubmissionResource)
             AppCatalogJPAUtils.getResource(
                 AppCatalogResourceType.GLOBUS_SUBMISSION, globusJobSubmission);
     em.getTransaction().commit();
     em.close();
     return globusJobSubmissionResource;
   } catch (ApplicationSettingsException e) {
     logger.error(e.getMessage(), e);
     throw new AppCatalogException(e);
   } finally {
     if (em != null && em.isOpen()) {
       if (em.getTransaction().isActive()) {
         em.getTransaction().rollback();
       }
       em.close();
     }
   }
 }
Ejemplo n.º 4
0
  @Override
  public void saveConference(
      String title,
      Date start,
      Date end,
      String room,
      String website,
      List<Stakeholder> stakeholders) {
    if (stakeholders == null) stakeholders = new ArrayList<>();
    Conference c = new Conference();
    List<Key> keys = new ArrayList<>();
    try {

      for (Stakeholder s : stakeholders) {
        keys.add(s.getId());
      }

      c = new Conference(title, start, end, room, website, keys);
      em.persist(c);
    } finally {
      em.close();
    }

    try {
      em = EMF.get().createEntityManager();

      for (Key k : keys) {
        Stakeholder s = em.find(Stakeholder.class, k);
        s.addConference(c.getId());
      }
    } finally {
      em.close();
    }
  }
Ejemplo n.º 5
0
 private boolean auto(String operation) {
   long startTime = System.currentTimeMillis();
   System.out.println("Operation: " + operation + "...");
   HibernateEntityManagerFactory emf = null;
   EntityManager em = null;
   try {
     Map<String, String> map = getPeristencePropertiesFixedMap();
     if (operation != null) {
       map.put("hibernate.hbm2ddl.auto", operation);
     }
     if (operation.equals("update")) {
       if (getDriver().equals(TestStation.Driver.derby)) {
         String url = map.get("hibernate.connection.url");
         if (!url.contains("create=true")) {
           url += ";create=true";
         }
         //                    if (!url.contains("logDevice=")) {
         //                        url += ";logDevice=" + getUserHome() + File.separator +
         // ".jtstand";
         //                    }
         map.put("hibernate.connection.url", url);
       }
     }
     emf =
         (HibernateEntityManagerFactory)
             Persistence.createEntityManagerFactory(getTestProject().getPun(), map);
     //            emf.getSessionFactory().getAllClassMetadata();
     //            System.out.println(emf.getSessionFactory().getAllClassMetadata());
     em = emf.createEntityManager();
     em.getTransaction().begin();
     em.getTransaction().commit();
     //            System.out.println("Closing entity manager");
     em.close();
     //            System.out.println("Closing entity manager factory");
     emf.close();
     System.out.println(
         "Database "
             + operation
             + " operation succeeded in "
             + Long.toString(System.currentTimeMillis() - startTime)
             + "ms");
     return true;
   } catch (Exception ex) {
     ex.printStackTrace();
     System.out.println(ex.getMessage());
     if (em != null && em.isOpen()) {
       em.close();
     }
     if (emf != null && emf.isOpen()) {
       emf.close();
     }
   }
   System.out.println(
       "Database "
           + operation
           + " operation failed in "
           + Long.toString(System.currentTimeMillis() - startTime)
           + "ms");
   return false;
 }
Ejemplo n.º 6
0
  @Override
  public void saveStakeholder(
      String name, String type, String email, String website, List<Conference> conferences) {
    if (conferences == null) conferences = new ArrayList<>();
    Stakeholder s = new Stakeholder();
    List<Key> keys = new ArrayList<>();
    try {

      for (Conference c : conferences) {
        keys.add(c.getId());
      }

      s = new Stakeholder(name, type, email, website, keys);
      em.persist(s);
    } finally {
      em.close();
    }

    try {
      em = EMF.get().createEntityManager();

      for (Key k : keys) {
        Conference c = em.find(Conference.class, k);
        c.addStakeholder(s.getId());
      }
    } finally {
      em.close();
    }
  }
  /**
   * 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();
  }
  /**
   * The merge method should copy all entity data into entity manager. Entity itself in not attached
   * nor persisted.
   */
  @Test
  public void entityEquality_mergeInto_EntityManager() {
    // load and detach entity
    EntityManager em1 = factory.createEntityManager();
    Person person1 = em1.find(Person.class, SIMON_SLASH_ID);
    em1.close();

    // change its property
    person1.setFirstName("New Name");

    // merge it into some entity manager
    EntityManager em2 = factory.createEntityManager();
    em2.merge(person1);

    // this change will be ignored
    person1.setFirstName("Ignored Change");

    Person person2 = em2.find(Person.class, SIMON_SLASH_ID);
    em2.close();

    // entity itself was not attached
    assertNotSame(person1, person2);
    // however, its changed data was
    assertEquals("New Name", person2.getFirstName());

    // changed data are NOT available in different entity manager
    EntityManager em3 = factory.createEntityManager();
    Person person3 = em3.find(Person.class, SIMON_SLASH_ID);
    em3.close();

    assertNotSame("New Name", person3.getFirstName());
  }
Ejemplo n.º 9
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);
    }
  }
  public void testDetach() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();

    Tooth tooth = new Tooth();
    Mouth mouth = new Mouth();
    em.persist(mouth);
    em.persist(tooth);
    tooth.mouth = mouth;
    mouth.teeth = new ArrayList<Tooth>();
    mouth.teeth.add(tooth);
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    mouth = em.find(Mouth.class, mouth.id);
    assertNotNull(mouth);
    assertEquals(1, mouth.teeth.size());
    tooth = mouth.teeth.iterator().next();
    em.detach(mouth);
    assertFalse(em.contains(tooth));
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.remove(em.find(Mouth.class, mouth.id));

    em.getTransaction().commit();
    em.close();
  }
Ejemplo n.º 11
0
  public void queryMedicalHistory4() {
    EntityManager em = emf.createEntityManager();
    Map medicals = new HashMap();
    long ssn = 0;
    EntityTransaction tran = em.getTransaction();
    tran.begin();
    String jpql = "select m from MedicalHistory2 m";
    Query q = em.createQuery(jpql);
    List<MedicalHistory2> ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      ssn = m.getId();
    }
    tran.commit();
    em.close();

    em = emf.createEntityManager();
    tran = em.getTransaction();
    tran.begin();
    jpql = "select m from MedicalHistory2 m where m.patient.ssn = " + ssn;
    q = em.createQuery(jpql);
    ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      assertMedicalHistory2(m);
    }
    tran.commit();
    em.close();

    findObj4(ssn);
  }
  @Override
  protected com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider.SignupResult
      signupUser(MyUsernamePasswordAuthUser user) {

    EntityManager em = JPA.em(JpaConstants.DB);

    UserHome userDao = new UserHome();

    User u = userDao.findByUsernamePasswordIdentity(user, em);
    if (u != null) {
      if (u.getEmailValidated()) {
        // This user exists, has its email validated and is active
        em.close();
        return SignupResult.USER_EXISTS;
      } else {
        // this user exists, is active but has not yet validated its
        // email
        em.close();
        return SignupResult.USER_EXISTS_UNVERIFIED;
      }
    }
    // The user either does not exist or is inactive - create a new one
    @SuppressWarnings("unused")
    User newUser = userDao.create(user, em);
    // Usually the email should be verified before allowing login, however
    // if you return
    // return SignupResult.USER_CREATED;
    // then the user gets logged in directly

    em.close();
    return SignupResult.USER_CREATED_UNVERIFIED;
  }
Ejemplo n.º 13
0
  @Test
  public void testCascadeAndFetchEntity() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Troop disney = new Troop();
    disney.setName("Disney");
    Soldier mickey = new Soldier();
    mickey.setName("Mickey");
    disney.addSoldier(mickey);
    em.persist(disney);
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Soldier soldier = em.find(Soldier.class, mickey.getId());
    assertFalse(Hibernate.isInitialized(soldier.getTroop()));
    em.getTransaction().commit();
    assertFalse(Hibernate.isInitialized(soldier.getTroop()));
    em.close();
    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Troop troop = em.find(Troop.class, disney.getId());
    em.remove(troop);
    // Fail because of HHH-1187
    em.getTransaction().commit();
    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();
  }
Ejemplo n.º 15
0
  public static void main(String[] args) {

    // Start EntityManagerFactory
    EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("black", new DBConnector().mysql);

    // First unit of work
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    // Persist data
    MessageHibModel MessageHib = new MessageHibModel("Hello World with JPA and JTA");
    em.persist(MessageHib);

    // Commit & close
    tx.commit();
    em.close();

    // Second unit of work
    EntityManager newEm = emf.createEntityManager();
    EntityTransaction newTx = newEm.getTransaction();
    newTx.begin();

    MessageHibModel m = new MessageHibModel();
    m.setText("Hello World with JPA and JTA");

    @SuppressWarnings("unchecked")
    List<EntityManager> MessageHibs =
        newEm
            .createQuery(
                "select m from MessageHibModel m where m.text like :sText order by m.text asc")
            .setParameter("sText", m.getText())
            .setFlushMode(FlushModeType.COMMIT)
            // .setHint("org.hibernate.cacheMode",org.hibernate.CacheMode.IGNORE)
            .setHint("org.hibernate.cacheable", true)
            .setHint("org.hibernate.readOnly", true)
            .setHint("org.hibernate.comment", "My Comment...")
            .setFirstResult(1)
            // .getSingleResult()
            .setMaxResults(20)
            .getResultList();

    System.out.println(MessageHibs.size() + " Message(s) found:");

    for (Object m1 : MessageHibs) {
      MessageHibModel loadedMsg = (MessageHibModel) m1;
      System.out.println(loadedMsg.getText());
    }

    newTx.commit();
    newEm.close();

    // Shutting down the application
    emf.close();
  }
Ejemplo n.º 16
0
  /** Test of an SQL query persisting the object and querying in a different txn. */
  public void testBasic2() {
    if (vendorID == null) {
      return;
    }
    try {
      EntityManager em = getEM();
      EntityTransaction tx = em.getTransaction();
      try {
        tx.begin();

        // Persist an object
        Person p = new Person(101, "Fred", "Flintstone", "*****@*****.**");
        p.setAge(34);
        em.persist(p);

        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.PERSON_ID FROM JPA_AN_PERSON P WHERE P.AGE_COL=34")
                .getResultList();
        assertEquals(1, result.size());
        Iterator iter = result.iterator();
        while (iter.hasNext()) {
          // Should be a Long or equivalent (type of "PERSON_ID" column (Person.personNum field));
          // Oracle returns BigDecimal
          Object obj = iter.next();
          assertTrue(
              "SQL query has returned an object of an incorrect type",
              Number.class.isAssignableFrom(obj.getClass()));
        }

        tx.rollback();
      } finally {
        if (tx.isActive()) {
          tx.rollback();
        }
        em.close();
      }
    } finally {
      clean(Person.class);
    }
  }
  @Test
  public void testMergeMultipleEntityCopiesAllowed() {
    Item item1 = new Item();
    item1.setName("item1");

    Hoarder hoarder = new Hoarder();
    hoarder.setName("joe");

    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.persist(item1);
    em.persist(hoarder);
    em.getTransaction().commit();
    em.close();

    // Get another representation of the same Item from a different EntityManager.

    em = getOrCreateEntityManager();
    Item item1_1 = em.find(Item.class, item1.getId());
    em.close();

    // item1_1 and item1_2 are unmodified representations of the same persistent entity.
    assertFalse(item1 == item1_1);
    assertTrue(item1.equals(item1_1));

    // Update hoarder (detached) to references both representations.
    hoarder.getItems().add(item1);
    hoarder.setFavoriteItem(item1_1);

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    // the merge should succeed because it does not have Category copies.
    // (CustomEntityCopyObserver does not allow Category copies; it does allow Item copies)
    hoarder = em.merge(hoarder);
    assertEquals(1, hoarder.getItems().size());
    assertSame(hoarder.getFavoriteItem(), hoarder.getItems().iterator().next());
    assertEquals(item1.getId(), hoarder.getFavoriteItem().getId());
    assertEquals(item1.getCategory(), hoarder.getFavoriteItem().getCategory());
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    hoarder = em.find(Hoarder.class, hoarder.getId());
    assertEquals(1, hoarder.getItems().size());
    assertSame(hoarder.getFavoriteItem(), hoarder.getItems().iterator().next());
    assertEquals(item1.getId(), hoarder.getFavoriteItem().getId());
    assertEquals(item1.getCategory(), hoarder.getFavoriteItem().getCategory());
    em.getTransaction().commit();
    em.close();

    cleanup();
  }
  @Test
  public void testInvalidTupleIndexAccess() {
    EntityManager em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    Customer c1 = new Customer();
    c1.setId("c1");
    c1.setAge(18);
    c1.setName("Bob");
    em.persist(c1);
    em.getTransaction().commit();
    em.close();

    // the actual assertion block
    em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    final CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
    Root<Customer> customerRoot = criteria.from(Customer.class);
    criteria.multiselect(customerRoot.get(Customer_.name), customerRoot.get(Customer_.age));
    List<Tuple> results = em.createQuery(criteria).getResultList();
    assertEquals(1, results.size());
    Tuple tuple = results.get(0);
    try {
      tuple.get(99);
      fail("99 is invalid index");
    } catch (IllegalArgumentException expected) {
    }

    try {
      tuple.get(99, String.class);
      fail("99 is invalid index");
    } catch (IllegalArgumentException expected) {
    }

    tuple.get(0, String.class);
    tuple.get(1, Integer.class);

    try {
      tuple.get(0, java.util.Date.class);
      fail("Date is invalid type");
    } catch (IllegalArgumentException expected) {
    }

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

    em = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete Customer").executeUpdate();
    em.getTransaction().commit();
    em.close();
  }
Ejemplo n.º 19
0
  @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();
  }
Ejemplo n.º 20
0
  @Test
  public void testJpaSecondLevelCache() {
    String jpql = "FROM Department d";

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query query = entityManager.createQuery(jpql);
    List<Department> departments = query.setHint(QueryHints.HINT_CACHEABLE, true).getResultList();
    entityManager.close();

    entityManager = entityManagerFactory.createEntityManager();
    query = entityManager.createQuery(jpql);
    departments = query.setHint(QueryHints.HINT_CACHEABLE, true).getResultList();
    entityManager.close();
  }
 public Resource get(ResourceType type, Object name) {
   EntityManager em = ResourceUtils.getEntityManager();
   em.getTransaction().begin();
   QueryGenerator generator;
   Query q;
   switch (type) {
     case WORKFLOW_DATA:
       generator = new QueryGenerator(WORKFLOW_DATA);
       //                generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID);
       generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name);
       q = generator.selectQuery(em);
       Workflow_Data eworkflowData = (Workflow_Data) q.getSingleResult();
       WorkflowDataResource workflowDataResource =
           (WorkflowDataResource) Utils.getResource(ResourceType.WORKFLOW_DATA, eworkflowData);
       em.getTransaction().commit();
       em.close();
       return workflowDataResource;
     case EXPERIMENT_METADATA:
       generator = new QueryGenerator(EXPERIMENT_METADATA);
       generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name);
       q = generator.selectQuery(em);
       Experiment_Metadata expMetadata = (Experiment_Metadata) q.getSingleResult();
       ExperimentMetadataResource experimentMetadataResource =
           (ExperimentMetadataResource)
               Utils.getResource(ResourceType.EXPERIMENT_METADATA, expMetadata);
       em.getTransaction().commit();
       em.close();
       return experimentMetadataResource;
     case GFAC_JOB_DATA:
       generator = new QueryGenerator(GFAC_JOB_DATA);
       generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name);
       q = generator.selectQuery(em);
       GFac_Job_Data gFacJobData = (GFac_Job_Data) q.getSingleResult();
       GFacJobDataResource gFacJobDataResource =
           (GFacJobDataResource) Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData);
       em.getTransaction().commit();
       em.close();
       return gFacJobDataResource;
     default:
       em.getTransaction().commit();
       em.close();
       logger.error(
           "Unsupported resource type for experiment data resource... ",
           new UnsupportedOperationException());
       throw new IllegalArgumentException(
           "Unsupported resource type for experiment data resource.");
   }
 }
Ejemplo n.º 22
0
 public List<Transportista> busquedaPersonalizada(BusquedaTransportistaCriteria criteria) {
   String query =
       "SELECT t FROM Transportista t WHERE t.empresa = :empresa AND t.eliminado = false";
   // Nombre
   if (criteria.isBuscarPorNombre() == true) {
     String[] terminos = criteria.getNombre().split(" ");
     for (int i = 0; i < terminos.length; i++) {
       query += " AND t.nombre LIKE '%" + terminos[i] + "%'";
     }
   }
   // Localidad
   if (criteria.isBuscarPorLocalidad() == true) {
     query = query + " AND t.localidad = " + criteria.getLocalidad().getId_Localidad();
   }
   // Provincia
   if (criteria.isBuscarPorProvincia() == true) {
     query = query + " AND t.localidad.provincia = " + criteria.getProvincia().getId_Provincia();
   }
   // Pais
   if (criteria.isBuscarPorPais() == true) {
     query = query + " AND t.localidad.provincia.pais = " + criteria.getPais().getId_Pais();
   }
   query = query + " ORDER BY t.nombre ASC";
   EntityManager em = PersistenceUtil.getEntityManager();
   TypedQuery<Transportista> typedQuery = em.createQuery(query, Transportista.class);
   typedQuery.setParameter("empresa", criteria.getEmpresa());
   List<Transportista> transportistas = typedQuery.getResultList();
   em.close();
   return transportistas;
 }
  @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(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();
     }
   }
 }
Ejemplo n.º 25
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();
     }
   }
 }
Ejemplo n.º 26
0
 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();
     }
   }
 }
Ejemplo n.º 27
0
 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();
     }
   }
 }
Ejemplo n.º 28
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
Ejemplo n.º 29
0
  private void initDialog() {
    initPhase = true;
    cmbDaysWeeks.setModel(
        new DefaultComboBoxModel(
            new String[] {SYSTools.xx("misc.msg.Days"), SYSTools.xx("misc.msg.weeks")}));
    cbWeightControlled.setText(
        SYSTools.xx("opde.medication.medproduct.wizard.subtext.weightControlled"));
    cbWeightControlled.setSelected(tradeForm.isWeightControlled());
    cbExpiresAfterOpened.setText(SYSTools.xx("tradeform.subtext.expiresAfterOpenedIn"));
    cbExpiresAfterOpened.setSelected(tradeForm.getDaysToExpireAfterOpened() != null);
    txtExpiresIn.setEnabled(cbExpiresAfterOpened.isSelected());
    cmbDaysWeeks.setEnabled(cbExpiresAfterOpened.isSelected());
    Pair<Integer, Integer> pair = TradeFormTools.getExpiresIn(tradeForm);
    if (pair != null) {
      txtExpiresIn.setText(
          pair.getFirst() > 0 ? pair.getFirst().toString() : pair.getSecond().toString());
      cmbDaysWeeks.setSelectedIndex(pair.getFirst() > 0 ? 0 : 1);
    }

    EntityManager em = OPDE.createEM();
    Query query = em.createQuery("SELECT m FROM DosageForm m ORDER BY m.preparation, m.usageText");
    cmbForm.setModel(new DefaultComboBoxModel(query.getResultList().toArray(new DosageForm[] {})));
    cmbForm.setRenderer(DosageFormTools.getRenderer(0));
    em.close();

    cmbForm.setSelectedItem(tradeForm.getDosageForm());
    txtZusatz.setText(SYSTools.catchNull(tradeForm.getSubtext()));

    btnAdd.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication"));
    btnEdit.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication"));
    initPhase = false;
  }
Ejemplo n.º 30
0
 private void setH2LockTimeout() {
   EntityManager manager = entityManagerFactory.createEntityManager();
   manager.getTransaction().begin();
   manager.createNativeQuery("SET DEFAULT_LOCK_TIMEOUT " + locktimeout).executeUpdate();
   manager.getTransaction().commit();
   manager.close();
 }