Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

In this page you can find the example usage for javax.persistence EntityManager close.

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Vacancy> getOffersForEmployee(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Vacancy> list = new LinkedList<>();
    try {/*from   w  w  w. j  a v a 2s . c  om*/
        em.getTransaction().begin();

        TypedQuery<Vacancy> query = em.createNamedQuery("OfferBid.findVacancyOffersForEmployee", Vacancy.class);
        query.setParameter("employee", employee);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public Persona getPersona(Persona persona) {
    EntityManager em = null;
    try {/*w ww.ja va  2s. c  o m*/
        em = getEntityManager();
        Query q = em.createQuery("select p from Persona p where p.id=:id");
        q.setParameter("id", persona.getId());
        List<Persona> list = q.getResultList();
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        } else {
            return null;
        }
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:fr.mby.portal.coreimpl.auth.DbPortalUserAuthenticationProvider.java

/** Init the DB with default users : user:user456 & admin:admin456 */
protected void initDefaultUsers() {
    final PortalUser user = this.buildPortalUser("user", "user456");
    final PortalUser admin = this.buildPortalUser("admin", "admin456");

    final EntityManager portalUserEm = this.portalUserEmf.createEntityManager();

    // Remove transaction
    portalUserEm.getTransaction().begin();

    final PortalUser foundAdmin = this.findPortalUserByLogin(portalUserEm, "admin");
    if (foundAdmin != null) {
        portalUserEm.remove(foundAdmin);
    }/*w ww.j  a v  a 2s.c o m*/

    final PortalUser foundUser = this.findPortalUserByLogin(portalUserEm, "user");
    if (foundUser != null) {
        portalUserEm.remove(foundUser);
    }

    portalUserEm.getTransaction().commit();

    // Insert transaction
    portalUserEm.getTransaction().begin();

    portalUserEm.persist(user);
    portalUserEm.persist(admin);

    portalUserEm.getTransaction().commit();

    portalUserEm.close();
}

From source file:com.yahoo.sql4d.indexeragent.meta.DBHandler.java

private void addUpdateDeleteEntity(Object entity, Action action) {
    EntityManager em = getEntityManager();
    try {// w w  w .j ava  2s  . c o m
        em.getTransaction().begin();
        switch (action) {
        case ADD:
            em.persist(entity);
            break;
        case UPDATE:
            em.merge(entity);
            break;
        case DELETE:
            em.remove(entity);
            break;
        }
    } catch (RuntimeException e) {
        log.error("Something wrong persisting/merging/removing entity {}, so rolling back . Exception is {}",
                entity, ExceptionUtils.getStackTrace(e));
        em.getTransaction().rollback();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
        em.close();
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Employee> getOffersForVacancy(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Employee> list = new LinkedList<>();
    try {//from www. j a va2 s.  c o  m
        em.getTransaction().begin();

        TypedQuery<Employee> query = em.createNamedQuery("OfferBid.findEmployeeOffersForVacancy",
                Employee.class);
        query.setParameter("vacancy", vacancy);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java

@Test
public void testUpdate() {
    EntityManager em = emf.createEntityManager();
    PrintedBookDAOImpl bdao = new PrintedBookDAOImpl();
    bdao.setManager(em);/* w  w  w . j av  a 2 s.  c  o  m*/
    em.getTransaction().begin();

    Book book = new Book();
    book.setName("Harry Potter");
    book.setISBN("123112315");
    book.setDescription("Book about Wizard!");
    book.setAuthors("J.K. Rowling");
    book.setDepartment(Department.Sport);
    book.setIdBook(1);

    PrintedBook pbook = new PrintedBook();
    pbook.setBook(book);
    pbook.setState(Boolean.FALSE);
    pbook.setCondition(Condition.New);
    pbook.setIdPrintedBook(2);
    bdao.update(pbook);

    PrintedBook b1 = bdao.find(pbook);
    em.getTransaction().commit();
    em.close();
    assertEquals(b1.getState(), Boolean.FALSE);
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Register a new task.//ww w. j ava2 s.c om
 *
 * @param task The task to register
 * @return The task registered
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Task createTask(final Task task) {
    if (task.getApplicationId() == null) {
        throw new BadRequestException("A valid application for the task" + " must be provided");
    }
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    task.setDateCreated(new Date());
    task.setUserName(getUser());
    task.setStatus(Task.STATUS.WAITING);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        Application app = em.find(Application.class, task.getApplicationId());
        if (app == null) {
            throw new BadRequestException("Application id not valid");
        }
        task.setApplicationDetail(app);
        em.persist(task);
        et.commit();
        log.debug("New task registered: " + task.getId());
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        log.error("Impossible to create a task");
        log.debug(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return task;
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPuthenticate() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*w w w . j  a va  2s  .  c o  m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();

            final Shadow shadow = persistInstance(manager, username, password);

            Assert.assertTrue(shadow.puthenticate(shadow, password));

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:ict.DoLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w  w .j  a  v  a 2 s.co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("WSPU");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        String _request = request.getParameter("AAA");
        String userID = new String(Base64.decodeBase64(_request));

        String _request_ = request.getParameter("BBB");
        String userPassword = new String(Base64.decodeBase64(_request_));

        //String userID = request.getParameter("userID");
        //String userPassword = request.getParameter("userPassword");
        User tmp = new User();
        tmp.setUserID(userID);
        tmp.setPassword(userPassword);
        System.out.println("*****" + tmp.getUserID());

        User user = entityManager.find(User.class, tmp.getUserID());
        if (user.getPassword().equals(tmp.getPassword())) {
            entityManager.getTransaction().commit();
            entityManager.close();
            entityManagerFactory.close();
            request.getSession(true).setAttribute("user", user.getUserName());
        }

    } catch (Exception e) {
        System.out.println("****ERROR:****" + e.getMessage());
    }
    response.sendRedirect("index.jsp");
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

@SuppressWarnings({ "MethodWithTooExceptionsDeclared" })
@NotNull/* w  w  w. j  a va2  s. co  m*/
public AbstractORQCalculator<?, ?> newORQCalculator(final @NotNull EntityManagerFactory emf,
        final @NotNull String offerTypeKey) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {
    EntityManager em = emf.createEntityManager();
    try {
        OfferType type = em.find(OfferType.class, offerTypeKey);
        if (type == null)
            throw new IllegalArgumentException("Unknow offer type: " + offerTypeKey);
        AbstractORQCalculator<?, ?> orqc = orqPark.getInstance(type);
        orqc.setConfigletProvider(this);
        return orqc;
    } finally {
        if (!em.isOpen())
            em.close();
    }
}