Ejemplo n.º 1
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);
  }
Ejemplo n.º 2
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.º 3
0
  @Test
  @RunOrder(5)
  public void deleteByEntityTest() {

    getForUpfate();
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
      transaction.begin();
      // ============= Query construction ============== //
      JpaQueryStream<Person> stream =
          JpaQueryProvider.delete(em, Person.class)
              .where()
              .equal(Person::getPersonalNo, PERSONAL_NO2)
              .and()
              .like(Person::getLastName, "lname%")
              .and()
              .startsWith(Person::getFirstName, "fname");
      int rows = stream.execute();
      // =============================================//
      transaction.commit();
      System.out.println();
      System.out.println("-------Entity----");
      System.out.println();
      System.out.format("deleted %s rows\n", rows);
      Assert.assertEquals("No expected row number was updated", rows, 1);
    } catch (Throwable ex) {
      rollback(transaction);
    } finally {
      em.close();
    }
  }
Ejemplo n.º 4
0
 @Override
 public R apply(final D input) {
   RuntimeException rootCause = null;
   for (int i = 0; i < retries; i++) {
     EntityTransaction db = Entities.get(this.entityType);
     try {
       R ret = this.function.apply(input);
       db.commit();
       return ret;
     } catch (RuntimeException ex) {
       db.rollback();
       if (Exceptions.isCausedBy(ex, OptimisticLockException.class)) {
         rootCause = Exceptions.findCause(ex, OptimisticLockException.class);
       } else if (Exceptions.isCausedBy(ex, LockAcquisitionException.class)) {
         rootCause = Exceptions.findCause(ex, LockAcquisitionException.class);
       } else {
         rootCause = ex;
         Logs.extreme().error(ex, ex);
         throw ex;
       }
       try {
         TimeUnit.MILLISECONDS.sleep(20);
       } catch (InterruptedException ex1) {
         Exceptions.maybeInterrupted(ex1);
       }
       continue;
     }
   }
   throw (rootCause != null
       ? rootCause
       : new NullPointerException(
           "BUG: Transaction retry failed but root cause exception is unknown!"));
 }
Ejemplo n.º 5
0
  public User editUser(Long userId, String password, long bitmap) {
    if (password.isEmpty()) {
      return null;
    }

    Privileges privileges = new Privileges(bitmap);
    EntityTransaction transaction = startSaveTransaction();

    User user = getUserById(userId);
    if (user != null) {
      user.setPassword(password);
      user.setCategoryRead(privileges.isCategoryRead());
      user.setCategoryWrite(privileges.isCategoryWrite());
      user.setCategoryDelete(privileges.isCategoryDelete());
      user.setItemRead(privileges.isItemRead());
      user.setItemWrite(privileges.isItemWrite());
      user.setItemDelete(privileges.isItemDelete());
      user.setItemCommentRead(privileges.isItemCommentRead());
      user.setItemCommentWrite(privileges.isItemCommentWrite());
      user.setItemCommentDelete(privileges.isItemCommentDelete());
      user.setUserPromote(privileges.isUserPromote());
      user.setUserDemote(privileges.isUserDemote());
      user.setUserDelete(privileges.isUserDelete());
    }

    try {
      entityManager.persist(user);
      transaction.commit();
      return user;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Ejemplo n.º 6
0
  public Category editCategory(
      Long categoryId, String name, String description, String overpassKeyValue, User updateUser) {
    if (updateUser == null || !updateUser.isCategoryWrite() || name.isEmpty()) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Category category = getCategoryById(categoryId);
    if (category != null) {
      category.setName(name);
      category.setDescription(description);
      category.setOverpassKeyValue(overpassKeyValue);
      category.setUpdateUser(updateUser);
      category.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(category);
      transaction.commit();
      return category;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Ejemplo n.º 7
0
  public Item editItem(
      Long itemId,
      String title,
      String description,
      BigDecimal price,
      Long categoryId,
      User updateUser) {
    if (updateUser == null || !updateUser.isItemWrite() || title.isEmpty() || price == null) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Item item = getItem(itemId);
    if (item != null) {
      item.setTitle(title);
      item.setDescription(description);
      item.setPrice(price);
      item.setCategory(getCategoryById(categoryId));
      item.setUpdateUser(updateUser);
      item.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(item);
      transaction.commit();
      return item;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
  public InterestRate getInterestRateByInterestRateId(String interestRateId) {

    // Obtains entity manager object
    EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();

    // Obtains transaction from entity manager
    EntityTransaction entr = entityManager.getTransaction();

    // -----------Begin transaction-----------
    InterestRate interestRate = null;
    try {
      entr.begin();
      // Get a list of accounts from DB
      TypedQuery<InterestRate> query =
          entityManager.createQuery(
              "SELECT i FROM " + InterestRate.class.getName() + " i where i.interestRateId = ?",
              InterestRate.class);
      query.setParameter(1, Integer.parseInt(interestRateId));
      interestRate = query.getSingleResult();

      entr.commit();
    } catch (Exception e) {
      entityManager.close();
    }
    // -----------End transaction-----------

    return interestRate;
  }
 public void modificar(Estado c) {
   EntityManager em = FactoryDAO.em;
   EntityTransaction etx = em.getTransaction();
   etx.begin();
   em.merge(c);
   etx.commit();
 }
Ejemplo n.º 10
0
  private void withBatch() {
    int entityCount = 100;
    // tag::batch-session-batch-insert-example[]
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
      entityManager = entityManagerFactory().createEntityManager();

      txn = entityManager.getTransaction();
      txn.begin();

      int batchSize = 25;

      for (int i = 0; i < entityCount; ++i) {
        Person Person = new Person(String.format("Person %d", i));
        entityManager.persist(Person);

        if (i % batchSize == 0) {
          // flush a batch of inserts and release memory
          entityManager.flush();
          entityManager.clear();
        }
      }

      txn.commit();
    } catch (RuntimeException e) {
      if (txn != null && txn.isActive()) txn.rollback();
      throw e;
    } finally {
      if (entityManager != null) {
        entityManager.close();
      }
    }
    // end::batch-session-batch-insert-example[]
  }
Ejemplo n.º 11
0
  private void withoutBatch() {
    // tag::batch-session-batch-example[]
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
      entityManager = entityManagerFactory().createEntityManager();

      txn = entityManager.getTransaction();
      txn.begin();

      for (int i = 0; i < 100_000; i++) {
        Person Person = new Person(String.format("Person %d", i));
        entityManager.persist(Person);
      }

      txn.commit();
    } catch (RuntimeException e) {
      if (txn != null && txn.isActive()) txn.rollback();
      throw e;
    } finally {
      if (entityManager != null) {
        entityManager.close();
      }
    }
    // end::batch-session-batch-example[]
  }
 /**
  * Retrieve a task list for the user. Tasks are retrieved from the storage for the user performing
  * the request.
  *
  * @return A list of tasks
  */
 private List<Task> retrieveTaskList() {
   List<Task> lstTasks = new LinkedList<>();
   EntityManager em = getEntityManager();
   EntityTransaction et = null;
   List<Object[]> taskList = null;
   try {
     et = em.getTransaction();
     et.begin();
     taskList =
         em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList();
     et.commit();
   } catch (RuntimeException re) {
     if (et != null && et.isActive()) {
       et.rollback();
     }
     log.error("Impossible to retrieve the task list");
     log.error(re);
     throw new RuntimeException("Impossible to access the task list");
   } finally {
     em.close();
   }
   if (taskList != null && !taskList.isEmpty()) {
     for (Object[] elem : taskList) {
       int idElem = 0;
       Task tmpTask = new Task();
       tmpTask.setId((String) elem[idElem++]);
       tmpTask.setDescription((String) elem[idElem++]);
       tmpTask.setState((Task.STATE) elem[idElem++]);
       tmpTask.setDateCreated((Date) elem[idElem]);
       lstTasks.add(tmpTask);
     }
   }
   return lstTasks;
 }
 /**
  * Updates or adds an agent to the database.
  *
  * @param agent The Agent you wish to modify or add in the database.
  */
 protected void updateAgentInDatabase(AgentImpl agent) {
   EntityManager em = null;
   EntityTransaction tx = null;
   try {
     em = emf.createEntityManager();
     tx = em.getTransaction();
     tx.begin();
     AgentImpl existing = getAgent(agent.getName(), agent.getOrganization(), em);
     if (existing == null) {
       em.persist(agent);
     } else {
       existing.setConfiguration(agent.getConfiguration());
       existing.setLastHeardFrom(agent.getLastHeardFrom());
       existing.setState(agent.getState());
       existing.setSchedulerRoles(agent.getSchedulerRoles());
       existing.setUrl(agent.getUrl());
       em.merge(existing);
     }
     tx.commit();
   } catch (RollbackException e) {
     logger.warn("Unable to commit to DB in updateAgent.");
     throw e;
   } finally {
     if (em != null) em.close();
   }
 }
  @AroundInvoke
  public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction trx = manager.getTransaction();
    boolean criador = false;

    try {
      if (!trx.isActive()) {
        // truque para fazer rollback no que já passou
        // (senão, um futuro commit, confirmaria até mesmo operações sem transação)
        trx.begin();
        trx.rollback();

        // agora sim inicia a transação
        trx.begin();

        criador = true;
      }

      return context.proceed();
    } catch (Exception e) {
      if (trx != null && criador) {
        trx.rollback();
      }

      throw e;
    } finally {
      if (trx != null && trx.isActive() && criador) {
        trx.commit();
      }
    }
  }
Ejemplo n.º 15
0
  public static void create(Localidad localidad) {

    EntityManager entityManager = PersistenceManager.getEntityManager();

    EntityTransaction tr = entityManager.getTransaction();

    tr.begin();

    try {
      entityManager.persist(localidad);
      tr.commit();
      System.out.println(
          "Creación de localidad:"
              + localidad.getNombre()
              + ", de la prov: "
              + localidad.getProvincia().getNombre()
              + " exitosa");
    } catch (Exception ex) {
      tr.rollback();
      System.err.println(
          "Error en LibroDAO.create"
              + "("
              + Thread.currentThread().getStackTrace()[1].getLineNumber()
              + "):"
              + ex.getLocalizedMessage());
    } finally {
      entityManager.close();
    }
  }
Ejemplo n.º 16
0
  /**
   * Remove launch permissions.
   *
   * @param accountIds
   */
  public void removePermissions(final List<String> accountIds) {

    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().remove(input);
              } catch (final Exception e) {
                LOG.error(e, e);
              }
              return true;
            }
          });

      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
 public void guardar(Estado c) {
   EntityManager em = FactoryDAO.em;
   EntityTransaction etx = em.getTransaction();
   etx.begin();
   em.persist(c);
   etx.commit();
 }
Ejemplo n.º 18
0
 // cr�ation d'objets
 public static void test1() throws ParseException {
   // contexte de persistance
   EntityManager em = getEntityManager();
   // cr�ation personnes
   p1 =
       new Personne(
           "Martin", "Paul", new SimpleDateFormat("dd/MM/yy").parse("31/01/2000"), true, 2);
   p2 =
       new Personne(
           "Durant", "Sylvie", new SimpleDateFormat("dd/MM/yy").parse("05/07/2001"), false, 0);
   // cr�ation adresses
   a1 = new Adresse("8 rue Boileau", null, null, "49000", "Angers", null, "France");
   a2 = new Adresse("Apt 100", "Les Mimosas", "15 av Foch", "49002", "Angers", "03", "France");
   a3 = new Adresse("x", "x", "x", "x", "x", "x", "x");
   a4 = new Adresse("y", "y", "y", "y", "y", "y", "y");
   // associations personne <--> adresse
   p1.setAdresse(a1);
   p2.setAdresse(a2);
   // d�but transaction
   EntityTransaction tx = em.getTransaction();
   tx.begin();
   // persistance des personnes
   em.persist(p1);
   em.persist(p2);
   // et des adresses a3 et a4 non li�es � des personnes
   em.persist(a3);
   em.persist(a4);
   // fin transaction
   tx.commit();
   // on affiche les tables
   dumpPersonne();
   dumpAdresse();
 }
  public List<InterestRate> getInterestRates() {

    // Obtains entity manager object
    EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();

    // Obtains transaction from entity manager
    EntityTransaction entr = entityManager.getTransaction();

    // -----------Begin transaction-----------
    List<InterestRate> interestRates = null;
    try {
      entr.begin();
      // Get a list of accounts from DB
      TypedQuery<InterestRate> query =
          entityManager.createQuery(
              "SELECT i FROM " + InterestRate.class.getName() + " i", InterestRate.class);
      interestRates = query.getResultList();
      entr.commit();
    } catch (Exception e) {
      entityManager.close();
    }
    // -----------End transaction-----------

    return interestRates;
  }
  public static void main(String[] args) {
    try {
      EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU");
      EntityManager manager = f.createEntityManager();
      Scanner in = new Scanner(System.in);
      System.out.print("Enter id to modify");
      int id = in.nextInt();
      in.nextLine();
      Emp e = manager.find(Emp.class, id);
      System.out.println("current details are");
      System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary());
      System.out.println("Enter name to update");
      String n = in.nextLine();
      System.out.println("Enter job to update");
      String j = in.nextLine();
      System.out.println("Enter salary to update");
      int s = in.nextInt();
      EntityTransaction t = manager.getTransaction();
      t.begin();
      e.setEname(n);
      e.setJob(j);
      e.setSalary(s);

      t.commit();
      manager.close();
      System.out.println("updated");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Ejemplo n.º 21
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);
    }
  }
Ejemplo n.º 22
0
 @Override
 public boolean apply(@Nullable Class aClass) {
   EntityTransaction tran = Entities.get(AccountEntity.class);
   try {
     List<AccountEntity> accounts = Entities.query(new AccountEntity());
     if (accounts != null && accounts.size() > 0) {
       for (AccountEntity account : accounts) {
         if (account.getCanonicalId() == null || account.getCanonicalId().equals("")) {
           account.setCanonicalId(genCanonicalId());
           LOG.debug(
               "putting canonical id "
                   + account.getCanonicalId()
                   + " on account "
                   + account.getAccountNumber());
         }
       }
     }
     tran.commit();
   } catch (Exception ex) {
     tran.rollback();
     LOG.error(
         "caught exception during upgrade, while attempting to generate and assign canonical ids");
     Exceptions.toUndeclared(ex);
   }
   return true;
 }
Ejemplo n.º 23
0
  public ItemComment editItemComment(
      Long itemCommentId, String text, Integer rating, User updateUser) {
    if (updateUser == null
        || !updateUser.isItemCommentWrite()
        || text.isEmpty()
        || rating == null) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    ItemComment itemComment = getItemComment(itemCommentId);
    if (itemComment != null) {
      itemComment.setText(text);
      itemComment.setRating(correctRating(rating));
      itemComment.setUpdateUser(updateUser);
      itemComment.setUpdateTimestamp(new Timestamp(new Date().getTime()));
    }

    try {
      entityManager.persist(itemComment);
      transaction.commit();
      return itemComment;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Ejemplo n.º 24
0
 public void updateContact(Contact cn, String id) {
   EntityTransaction et = em.getTransaction();
   et.begin();
   Query query = em.createQuery("UPDATE c from Contact c WHERE c.id=" + id);
   query.executeUpdate();
   et.commit();
 }
Ejemplo n.º 25
0
  public User createUser(String username, String password, long bitmap) {
    if (username.isEmpty() || password.isEmpty()) {
      return null;
    }

    Privileges privileges = new Privileges(bitmap);
    EntityTransaction transaction = startSaveTransaction();

    User user =
        new User(
            username,
            password,
            privileges.isCategoryRead(),
            privileges.isCategoryWrite(),
            privileges.isCategoryDelete(),
            privileges.isItemRead(),
            privileges.isItemWrite(),
            privileges.isItemDelete(),
            privileges.isItemCommentRead(),
            privileges.isItemCommentWrite(),
            privileges.isItemCommentDelete(),
            privileges.isUserPromote(),
            privileges.isUserDemote(),
            privileges.isUserDelete());

    try {
      entityManager.persist(user);
      transaction.commit();
      return user;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Ejemplo n.º 26
0
 @Override
 public void delete(Object instance) {
   EntityTransaction tx = manager.getTransaction();
   tx.begin();
   manager.remove(instance);
   tx.commit();
 }
Ejemplo n.º 27
0
  public Item createItem(
      String title, String description, BigDecimal price, Long categoryId, User createUser) {
    if (createUser == null
        || !createUser.isItemWrite()
        || title.isEmpty()
        || price == null
        || categoryId == 0) {
      return null;
    }

    EntityTransaction transaction = startSaveTransaction();

    Item item =
        new Item(getCategoryById(categoryId), title, description, price, createUser, createUser);

    try {
      entityManager.persist(item);
      transaction.commit();
      return item;
    } catch (Exception e) {
      transaction.rollback();
    }

    return null;
  }
Ejemplo n.º 28
0
  /**
   * Add launch permissions.
   *
   * @param accountIds
   */
  public void addPermissions(final List<String> accountIds) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().add(input);
              } catch (final Exception e) {
                try {
                  final User user = Accounts.lookupUserById(input);
                  ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                } catch (AuthException ex) {
                  try {
                    final User user = Accounts.lookupUserByAccessKeyId(input);
                    ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                  } catch (AuthException ex1) {
                    LOG.error(ex1, ex1);
                  }
                }
              }
              return true;
            }
          });
      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
Ejemplo n.º 29
0
  void markAsBroken(ETask task, EntityManager em) {
    EntityTransaction et = em.getTransaction();

    et.begin();
    task.setStatus(ETask.statusSysError);
    et.commit();
  }
Ejemplo n.º 30
0
  private void getForUpfate() {

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
      JpaQueryStream<Person> stream =
          JpaQueryProvider.select(em, Person.class)
              .where()
              .equal(Person::getPersonalNo, PERSONAL_NO2)
              .and()
              .like(Person::getLastName, "lname%")
              .and()
              .startsWith(Person::getFirstName, "fname");
      Person person = stream.getFirst();
      transaction.begin();
      if (person == null) {
        Person newPerson = QueryTest.initPerson();
        em.persist(newPerson);
        person = newPerson;
      }
      transaction.commit();
    } catch (Throwable ex) {
      rollback(transaction);
    } finally {
      em.close();
    }
  }