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:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java

@Test
public void testDelete() {
    EntityManager em = emf.createEntityManager();
    PrintedBookDAOImpl bdao = new PrintedBookDAOImpl();
    bdao.setManager(em);//w w w.  ja  va 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(1);

    bdao.delete(pbook);
    em.getTransaction().commit();
    List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList();

    em.close();
    assertEquals(books.size(), 1);
}

From source file:BO.UserHandler.java

public boolean login(VUser u) {

    EntityManager em;
    EntityManagerFactory emf;/*from  w  w w  .j  av  a 2  s .  co  m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {

        Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email");
        q.setParameter("email", u.getEmail());
        q.setMaxResults(1);
        q.getSingleResult();
        return true;
    } catch (NoResultException e) {
        em.getTransaction().begin();
        User userToInsert = new User(u.getEmail());
        em.persist(userToInsert);
        em.flush();
        em.getTransaction().commit();
        return true;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

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

public PersonaFirma findPersonaFirma(Long idPersona, String firma) {
    EntityManager em = null;
    try {//  w  w  w .  j  a va2 s .c  o m
        em = getEntityManager();
        Query q = em.createQuery(
                "select distinct pf from PersonaFirma pf where pf.persona.id=:idPersona and pf.firma.nombre=:firma");
        q.setParameter("idPersona", idPersona);
        q.setParameter("firma", firma);
        List<PersonaFirma> list = q.getResultList();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

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

public PersonaFirma findPersonaFirma(Long idPersona, Long idFirma) {
    EntityManager em = null;
    try {/*w  ww. jav  a2  s .com*/
        em = getEntityManager();
        Query q = em.createQuery(
                "select distinct pf from PersonaFirma pf where pf.persona.id=:idPersona and pf.firma.id=:idFirma");
        q.setParameter("idPersona", idPersona);
        q.setParameter("idFirma", idFirma);
        List<PersonaFirma> list = q.getResultList();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

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

public Persona obtenerPersonaVacia() {
    EntityManager em = null;
    try {//  ww  w.j  a va 2s .c  o m
        em = getEntityManager();
        Query q = em.createQuery(
                "select distinct p from Persona p left join fetch p.personaFirmasCollection where p.id=1");
        List<Persona> list = q.getResultList();
        if (list != null && list.size() > 0) {
            Persona persona = list.get(0);
            Hibernate.initialize(persona.getPersonaFirmasCollection());
            return persona;
        }
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.noorganization.instalist.server.api.CategoriesResource.java

/**
 * Updates the category./*from  w w  w.  j  av  a  2  s  .  c om*/
 * @param _uuid The uuid of the category to update.
 * @param _entity A category with updated information.
 */
@PUT
@TokenSecured
@Path("{categoryuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _uuid,
        CategoryInfo _entity) throws Exception {
    if (_entity.getName() == null)
        return ResponseFactory.generateBadRequest(CommonEntity.NO_DATA_RECVD);
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_uuid))
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    Instant changedDate = Instant.now();
    if (_entity.getLastChanged() != null) {
        changedDate = _entity.getLastChanged().toInstant();
        if (changedDate.isAfter(Instant.now()))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    UUID categoryUUID;
    try {
        categoryUUID = UUID.fromString(_uuid);
    } catch (IllegalArgumentException e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ICategoryController categoryController = ControllerFactory.getCategoryController(manager);
    try {
        categoryController.update(_groupId, categoryUUID, _entity.getName(), changedDate);
    } catch (NotFoundException e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("Category was not " + "found."));
    } catch (GoneException e) {
        return ResponseFactory.generateGone(new Error().withMessage("Category was already " + "deleted."));
    } catch (ConflictException e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("Sent sategory is in " + "conflict with saved one."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from w w w . ja va2 s  . c  om*/
@Path("users.json")
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = {
        @RestParameter(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING),
        @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
@SuppressWarnings("unchecked")
public String getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
        throws IOException {
    if (limit < 1) {
        limit = 100;
    }
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("users").setMaxResults(limit).setFirstResult(offset);
        q.setParameter("o", securityService.getOrganization().getId());
        List<JpaUser> jpaUsers = q.getResultList();
        JSONArray jsonArray = new JSONArray();
        for (JpaUser user : jpaUsers) {
            Set<String> roles = user.getRoles();
            jsonArray.add(toJson(new User(user.getUsername(), user.getOrganization(),
                    roles.toArray(new String[roles.size()]))));
        }
        return jsonArray.toJSONString();
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:BO.UserHandler.java

public boolean updateDeviceToken(VUser u) {
    EntityManager em;
    EntityManagerFactory emf;/*from  w w  w.  j  a va  2 s.  c  o  m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();
    System.out.println("Updating token: " + u.getDeviceToken());
    try {
        em.getTransaction().begin();
        User user;
        user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email")
                .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult();
        user.setDeviceToken(u.getDeviceToken());
        em.persist(user);
        em.flush();
        em.getTransaction().commit();

        return true;
    } catch (NoResultException e) {
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }

}

From source file:in.bookmylab.jpa.JpaDAO.java

public User saveUser(User user, boolean savePassword) {
    EntityManager em = emf.createEntityManager();
    try {// w  w  w .  j  a va2s.  c  o m
        user.password = Utils.hashPassword(user.password);
        em.getTransaction().begin();
        if (user.userId == null) {
            grantDefaultRoleToUser(em, user);
            em.persist(user);
        } else {
            user = em.merge(user);
            if (savePassword) {
                Query q = em.createNamedQuery("User.setPassword");
                q.setParameter("password", user.password);
                q.setParameter("userId", user.userId);
                q.executeUpdate();
            }
        }
        em.getTransaction().commit();
    } finally {
        em.clear();
        em.close();
    }
    return user;
}

From source file:org.noorganization.instalist.server.api.UnitResource.java

/**
 * Updates the unit./*  w w w  . j  a v a 2 s. com*/
 * @param _groupId The id of the group containing the unit.
 * @param _unitUUID The existing Unit-UUID to update.
 * @param _entity The data for update.
 */
@PUT
@TokenSecured
@Path("{unituuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putUnit(@PathParam("groupid") int _groupId, @PathParam("unituuid") String _unitUUID,
        UnitInfo _entity) throws Exception {
    UUID toUpdate;
    try {
        toUpdate = UUID.fromString(_unitUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant changeDate;
    if (_entity.getLastChanged() == null)
        changeDate = Instant.now();
    else {
        changeDate = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(changeDate))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }
    if ((_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getUUID() != null && !_entity.getUUID().equals(_unitUUID)))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IUnitController unitController = ControllerFactory.getUnitController(manager);
    try {
        unitController.update(_groupId, toUpdate, _entity.getName(), changeDate);
    } catch (NotFoundException _e) {
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The unit to change " + "was not found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(
                new Error().withMessage("The unit to change was " + "not found since it has been deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "lead to a conflict with saved unit."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}