Java Code Examples for javax.persistence.EntityManager.close()

The following are Jave code examples for showing how to use close() of the javax.persistence.EntityManager class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: full-javaee-app   File: CandidatePersistence.java   View Source Code Vote up 6 votes
public static Candidates getCandidateByEmail(String email) {
    if (email != null && !email.isEmpty() && CustomUtilities.isValidEmail(email)) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        String query = "SELECT candidate FROM Candidates candidate WHERE candidate.email =:email";
        try {
            TypedQuery<Candidates> q = em.createQuery(query, Candidates.class);
            q.setParameter("email", email);
            return q.getSingleResult();
        } catch (Exception e) {

        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 2
Project: SqlSauce   File: DatabaseWrapper.java   View Source Code Vote up 6 votes
/**
 * So you want to load an entity, set some data, and save it again, without detaching it from the persistence
 * context and without bothering with the EntityManager?
 * Look no further! Functional programming to the rescue, just pass a function that does the required transformation
 * on the entity.
 * <p>
 * NOTE that this will create a new instance of the entity if it does not exist yet.
 *
 */
@Nonnull
public <E extends SaucedEntity<I, E>, I extends Serializable> E findApplyAndMerge(@Nonnull final Transfiguration<I, E> transfiguration)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        return this.lockedWrappedTransformFunc(transfiguration).apply(em);
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to find, apply and merge entity id %s of class %s on DB %s",
                transfiguration.key.id.toString(), transfiguration.key.clazz.getName(),
                this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 3
Project: Pet-Supply-Store   File: ProductRepository.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public long createEntity(Product entity) {
	PersistenceProduct product = new PersistenceProduct();
	product.setName(entity.getName());
	product.setDescription(entity.getDescription());
	product.setListPriceInCents(entity.getListPriceInCents());
	
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceCategory cat = em.find(PersistenceCategory.class, entity.getCategoryId());
        if (cat != null) {
        	product.setCategory(cat);
        	em.persist(product);
        } else {
        	product.setId(-1L);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return product.getId();
}
 
Example 4
Project: BecomeJavaHero   File: App4.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	// begining of transaction
	em.getTransaction().begin();
	
	// Creating query in the way very similar to SQL
	Query query = em.createQuery("Select r from Role r where r.name = :name");
	query.setParameter("name", "ordinary");
	
	// We obtaining result as a list of entities
	List<Role> roles = query.getResultList();
	
	for (Role role : roles) {
		System.out.println(role.getName());
		for (User u : role.getUsers()) {
			System.out.println("     " + u.getLastName());
		}
	}
	
	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
Example 5
Project: java-jdbc   File: HibernateTest.java   View Source Code Vote up 6 votes
@Test
public void jpa_with_parent_and_active_span_only() {

  try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) {
    EntityManagerFactory entityManagerFactory = Persistence
        .createEntityManagerFactory("jpa_active_span_only");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    entityManager.getTransaction().begin();
    entityManager.persist(new Employee());
    entityManager.persist(new Employee());
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();
  }

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(11, spans.size());
  checkSameTrace(spans);
  assertNull(mockTracer.activeSpan());
}
 
Example 6
Project: full-javaee-app   File: ConversationDataAccessObject.java   View Source Code Vote up 6 votes
public static Conversations persist (Conversations conversation) {
    if (conversation != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(conversation);
            trans.commit();
            return conversation;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 7
Project: full-javaee-app   File: ClientPipelineDataAccessObject.java   View Source Code Vote up 6 votes
public static ClientPipelines getByClientAndCandidateID (int clientID, int candidateID) {
    if (clientID > 0 && candidateID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        try {
            String query = "SELECT elt FROM ClientPipelines elt WHERE elt.clientID = :clientID AND elt.candidateID = :candidateID";
            TypedQuery<ClientPipelines> q = em.createQuery(query, ClientPipelines.class);
            q.setParameter("clientID", clientID);
            q.setParameter("candidateID", candidateID);
            return q.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 8
Project: aries-jpa   File: CarServiceWithEmfImpl.java   View Source Code Vote up 5 votes
@Override
public Car getCar(String id) {
    EntityManager em = emf.createEntityManager();
    try {
        return em.find(Car.class, id);
    } finally {
        em.close();
    }
}
 
Example 9
Project: git-rekt   File: BookingService.java   View Source Code Vote up 5 votes
/**
 * Returns the list of bookings that should be displayed in the daily registry for today's
 * date.
 */
public List<Booking> getDailyRegistry() {
    List<Booking> results;
    EntityManager entityManager = HibernateUtil.getEntityManager();
    String queryString = "FROM Booking WHERE isCheckedIn = true "
            + "OR trunc(sysdate) BETWEEN checkInDate and checkOutDate";
    Query q = entityManager.createQuery(queryString);
    results = q.getResultList();
    entityManager.close();
    return results;
}
 
Example 10
Project: bibliometrics   File: UserRegistrationServlet.java   View Source Code Vote up 5 votes
private void registrate(User user, String plainTextPassword) {		  
  generatePassword(user, plainTextPassword);
  LOGGER.info("persisting user " + user.getUsername() + " with password " + user.getPassword() + " and salt " + user.getSalt());
  EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
  EntityManager em = emf.createEntityManager();
  EntityTransaction tx = em.getTransaction();
  tx.begin();
  em.persist(user);
  LOGGER.info("user persisted");
  tx.commit();
  em.close();
}
 
Example 11
Project: aries-jpa   File: AbstractCarJPAITest.java   View Source Code Vote up 5 votes
/**
 * Create, find and delete car using resource local transactions
 * @param emf
 * @throws BundleException
 */
protected void carLifecycleRL(EntityManager em) throws BundleException {
    em.getTransaction().begin();
    Car car = createBlueCar();
    em.persist(car);
    em.getTransaction().commit();

    Car car2 = em.find(Car.class, BLUE_PLATE);
    assertBlueCar(car2);
    em.getTransaction().begin();
    em.remove(car2);
    em.getTransaction().commit();
    em.close();
}
 
Example 12
Project: aries-jpa   File: CarServiceWithMultiAnnotationImpl.java   View Source Code Vote up 5 votes
@Override
public void addCar(Car car) {
    EntityManager localEm = emf.createEntityManager();
    localEm.persist(car);
    localEm.flush();
    localEm.close();
}
 
Example 13
Project: git-rekt   File: GuestService.java   View Source Code Vote up 5 votes
public List<Guest> getCurrentlyCheckedInGuests() {
    EntityManager entityManager = HibernateUtil.getEntityManager();
    String query = "SELECT b.guest FROM Booking AS b WHERE b.isCheckedIn = true";
    Query q = entityManager.createQuery(query);
    List<Guest> results = q.getResultList();
    entityManager.close();
    return results;
}
 
Example 14
Project: full-javaee-app   File: CertificationPersistence.java   View Source Code Vote up 5 votes
public static Certifications getByID(int certificationID) {
    if (certificationID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        Certifications certification = em.find(Certifications.class, certificationID);
        em.close();
        return certification;
    }
    return null;
}
 
Example 15
Project: sumo   File: PluginManagerDialog.java   View Source Code Vote up 5 votes
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    Object[] selected = inactiveList.getSelectedValues();
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    for (Object plugin : selected) {
        Plugins p = (Plugins) plugin;
        p.setActive(true);
        inactivemodel.removeElement(p);
        activemodel.addElement(p);
        p = em.merge(p);
        em.persist(p);
    }
    em.getTransaction().commit();
    em.close();
}
 
Example 16
Project: Java-9-Programming-Blueprints   File: FileFinder.java   View Source Code Vote up 5 votes
private void purgeExistingFileInfo() {
    final EntityManager em = factory.createEntityManager();
    em.getTransaction().begin();
    em.createNativeQuery("delete from fileinfo").executeUpdate();
    em.getTransaction().commit();
    em.close();
}
 
Example 17
Project: campingsimulator2017   File: EmployeeDAO.java   View Source Code Vote up 5 votes
/**
 * Find an Employee by his first name.
 * @param firstName First name of the Employee.
 * @return The Employee with the matching first name.
 */
public List<Employee> findByFirstName(String firstName) {
    EntityManager em = HibernateUtil.getEntityManagerFactory().createEntityManager();

    String hql = "from Employee where firstName = :firstName";
    Query query = em.createQuery(hql);
    query.setParameter("firstName", firstName);

    List resultList = query.getResultList();

    em.close();

    return resultList;
}
 
Example 18
Project: ChronoBike   File: UsuarioJpaController.java   View Source Code Vote up 5 votes
public int getPersonaCount() {
        EntityManager em = getEntityManager();
        try {
//            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
//            Root<Usuario> rt = cq.from(Usuario.class);
//            cq.select(em.getCriteriaBuilder().count(rt));
//            Query q = em.createQuery(cq);
//            return ((Long) q.getSingleResult()).intValue();
            //String _user = "a";
            //String a = em.createQuery("select u.Rol from Usuarios u where Id=:ID and Pass='a'").setParameter("ID", _user);
            String pam1 = "a";
            String pam2 = "a";
            Query q = em.createNativeQuery(String.format(SQL_ISBANNED, pam1, pam2));
            //q = q.setParameter("pam1", "a");
            System.out.println(">>Uuser: " + q.toString());
            System.out.println(">>Uuser: " + q.getSingleResult());
//            List<Object[]> usuarios = q.getResultList();
//            
//            for(Object[] u : usuarios){
//                System.out.println(">>Uuser: " + u[0]);
//                System.out.println(">>Rool: " + u[1]);
//            }
            
            //System.out.println(">>>>>>>: " + a);

            return 1;
        } finally {
            em.close();
        }
    }
 
Example 19
Project: datatable-java   File: DatatableDAOImpl.java   View Source Code Vote up 4 votes
private <R> List<R> findAllImpl2(final DatatableQuery<R, T> input, final Specifications<T> specifications,
      final Pageable pageable) {
      
      // create query
  	final EntityManager entityManager = entityManagerFactory.createEntityManager();
      final CriteriaBuilder qb = entityManager.getCriteriaBuilder();        
      final CriteriaQuery<R> cq = qb.createQuery(input.getQueryClass());

      // Etablir entité racine
      final Root<T> from = cq.from(this.entity);
      
      // select for custom class
      final List<Selection<?>> selectList = new ArrayList<Selection<?>>();
      if (input.getGroupByColumns() != null) {
          DatatableHelper.getExpressions(from, input.getGroupByColumns(), selectList);
      } else {
          DatatableHelper.getExpressions(from, input.getColumns(), selectList);
      }
      cq.multiselect(selectList);

      // where
      if (specifications != null) {
          cq.where(specifications.toPredicate(from, cq, qb));
      }

      // group by
      if (input.getGroupByColumns() != null && !input.getGroupByColumns().isEmpty()) {
          final List<Expression<?>> groupByList = new ArrayList<Expression<?>>();
          DatatableHelper.getExpressions(from, input.getGroupByColumns(), groupByList);
          cq.groupBy(groupByList);
      }

      // order by
      if (pageable != null && pageable.getSort() != null) {
          cq.orderBy(DatatableHelper.getOrderBy(from, qb, pageable));
      }

      // page limit
      final TypedQuery<R> q = entityManager.createQuery(cq);
      if (pageable != null) {
      	LOGGER.log(Level.FINE, "Pageable: offset: {0}, page size: {1}", new Object[]{pageable.getOffset(), pageable.getPageSize()});
          q.setFirstResult(pageable.getOffset());
          q.setMaxResults(pageable.getPageSize());
      }

      // execute query
      final List<R> ret = q.getResultList();
      entityManager.close();
return ret;
  }
 
Example 20
Project: unibave-backend   File: Main.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
    EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("unibave-jpa");
    //org.hibernate.jpa.HibernatePersistenceProvider
    
    //adiciona
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Aluno ramon = new Aluno();
    ramon.setNome("Ramon");
    ramon.setCidade("Cidade Azul");

    AlunoContato contato = new AlunoContato();
    contato.setTelefone("48999999999");
    //em.persist(contato);
    ramon.addContato(contato);
    
    em.persist(ramon);
    tx.commit();
    em.close();
    //lista
    em = emf.createEntityManager();
    List<Aluno> alunos = em.createNamedQuery("aluno.lista", Aluno.class)
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(a -> {
        System.out.println(a);
        a.getContatos().forEach(System.out::println);
    });
    em.close();
    //lista por cidade
    em = emf.createEntityManager();
    alunos = em.createNamedQuery("aluno.listaPorCidade", Aluno.class)
            .setParameter("cidade", "Cidade Azul")
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(System.out::println);
    em.close();
    //atualiza
    em = emf.createEntityManager();
    tx = em.getTransaction();
    tx.begin();
    ramon = em.find(Aluno.class, ramon.getCodigo());
    ramon.setCidade("Tubarão");
    em.merge(ramon);
    tx.commit();
    //deleta
    tx = em.getTransaction();
    tx.begin();
    em.remove(ramon);
    tx.commit();
    em.close();      
    
    emf.close();
}