Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from  w ww  .  jav  a  2 s .com*/
 */
@Override
public <T extends BaseEntity> void delete(Class<T> entity, Object primaryKey) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        T entityToDelete = em.find(entity, primaryKey);
        if (entityToDelete == null) {
            LOGGER.warn("Entity couldn't be deleted as it doesn't exists in DB: [{}]", entity);
        } else {
            em.remove(entityToDelete);
            em.getTransaction().commit();
        }
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:ict.DoLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w  .j av  a2  s.c  o 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:com.enioka.jqm.tools.JqmEngine.java

private void purgeDeadJobInstances(EntityManager em, Node node) {
    em.getTransaction().begin();//  w w  w.j  a va  2  s. co m
    for (JobInstance ji : em
            .createQuery("SELECT ji FROM JobInstance ji WHERE ji.node = :node", JobInstance.class)
            .setParameter("node", node).getResultList()) {
        History h = em.find(History.class, ji.getId());
        if (h == null) {
            h = Helpers.createHistory(ji, em, State.CRASHED, Calendar.getInstance());
            Message m = new Message();
            m.setJi(ji.getId());
            m.setTextMessage(
                    "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash");
            em.persist(m);
        }

        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate();
    }
    em.getTransaction().commit();
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}/config", method = RequestMethod.PUT)
@Secured("ROLE_USER")
public ResponseEntity<Integer> setSliceConfiguration(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @RequestBody final SliceConfiguration config, @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    // TODO: put that to sliceProvider
    EntityManager entityManager = emf.createEntityManager();
    final TxFrame txf = new TxFrame(entityManager);
    try {//ww w  .  jav  a2  s . c  o m
        final Slice slice = entityManager.find(Slice.class, sliceId);
        if (config.getSize() != null) {
            final Subspace subspace = entityManager.find(Subspace.class, subspaceId);

            subspace.releaseSpace(slice.getTotalStorageSize());
            subspace.requestSpace(config.getSize());
        }
        slice.setConfiguration(config);
        txf.commit();
    } finally {
        txf.finish();
    }
    sliceProvider.invalidate(sliceId);
    subspaceProvider.invalidate(subspaceId);

    return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public SubscribedResource readSubscribedResourceById(int userid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    return entityManager.find(SubscribedResource.class, userid);

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public BakerUser readBakerUserById(int userid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    return entityManager.find(BakerUser.class, userid);

    //      Query q = entityManager.createQuery("SELECT m FROM BakerUser m WHERE m.id=" + userid );      
    //      return (q.getResultList().size()==0)?null:(BakerUser) q.getSingleResult();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public Product readProductByID(long id) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Product u = entityManager.find(Product.class, id);
    return u;//from   w  w  w  .ja v  a  2  s.c  o  m
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Path("{id}/markAllRead")
public Response markAllRead(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("allBefore") long timeMillis) {
    EntityManager em;
    EntityTransaction tx;//from w  ww .  j a  v a 2s. com
    User user;
    Feed feed;
    Date newDate;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();

    tx.begin();

    try {
        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        newDate = new Date(timeMillis);
        if (feed.getReadAllBefore() == null || feed.getReadAllBefore().before(newDate)) {
            feed.setReadAllBefore(newDate);
            em.persist(feed);
        }

        em.createQuery(
                "delete from FeedItem fi where fi.feed = :feed and fi.data.date < :date and not fi.starred and not fi.exported and size(fi.tags) = 0")
                .setParameter("feed", feed).setParameter("date", newDate).executeUpdate();

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

private boolean unregister(DzRegPK registryKey, Timestamp today) {
    EntityManager em = null;
    PersistentServiceFactory psf = null;

    try {//from www.jav a 2s.c  om
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        em.getTransaction().begin();
        DzReg r = em.find(DzReg.class, registryKey);
        r.setActive(_INACTIVE);
        r.setInsertedDt(today);
        em.getTransaction().commit();

        return true;
    } catch (javax.persistence.NoResultException nre) {
        em.getTransaction().rollback();
        log.error(registryKey + " not found!");
        return false;
    } catch (Exception ex) {
        em.getTransaction().rollback();
        return false;
    } finally {
        em.close();
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public BakerProperty readPropertyByID(int propid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    BakerProperty u = entityManager.find(BakerProperty.class, propid);
    return u;/*  ww  w.  ja va  2 s  . c  om*/

}