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:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

/**
 * Deletes a previously persisted resource from the database.
 *
 * @throws Exception if anything goes wrong
 *//*  w  w w  .  ja  v a2 s. co  m*/
private void teardownResourceEnvironment() throws Exception {
    if (parentResource != null) {

        List<Integer> deletedIds = resourceManager.uninventoryResource(overlord, parentResource.getId());
        for (Integer deletedResourceId : deletedIds) {
            resourceManager.uninventoryResourceAsyncWork(overlord, deletedResourceId);
        }

        getTransactionManager().begin();
        EntityManager em = getEntityManager();
        try {
            // Remove the child first.
            ResourceType deleteMeType = em.find(ResourceType.class, childResourceType.getId());
            em.remove(deleteMeType);

            deleteMeType = em.find(ResourceType.class, parentResourceType.getId());
            em.remove(deleteMeType);

            getTransactionManager().commit();
        } catch (Exception e) {
            try {
                System.out.println(e);
                getTransactionManager().rollback();
            } catch (Exception ignore) {
            }

            throw e;
        } finally {
            em.close();
        }
    }
}

From source file:com.jada.admin.contactus.ContactUsMaintAction.java

public ActionForward language(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {

    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    ContactUsMaintActionForm form = (ContactUsMaintActionForm) actionForm;
    if (form == null) {
        form = new ContactUsMaintActionForm();
    }/* ww  w .  j a va2  s  .  c  o m*/

    Site site = getAdminBean(request).getSite();
    initSiteProfiles(form, site);

    ContactUs contactUs = em.find(ContactUs.class, Format.getLong(form.getContactUsId()));

    form.setContactUsNameLangFlag(false);
    form.setContactUsDescLangFlag(false);
    form.setContactUsNameLang(contactUs.getContactUsLanguage().getContactUsName());
    form.setContactUsDescLang(contactUs.getContactUsLanguage().getContactUsDesc());
    if (!form.isSiteProfileClassDefault()) {
        Iterator<?> iterator = contactUs.getContactUsLanguages().iterator();
        Long siteProfileClassId = form.getSiteProfileClassId();
        while (iterator.hasNext()) {
            ContactUsLanguage contactUsLanguage = (ContactUsLanguage) iterator.next();
            if (contactUsLanguage.getSiteProfileClass().getSiteProfileClassId().equals(siteProfileClassId)) {
                if (contactUsLanguage.getContactUsName() != null) {
                    form.setContactUsNameLangFlag(true);
                    form.setContactUsNameLang(contactUsLanguage.getContactUsName());
                }
                if (contactUsLanguage.getContactUsDesc() != null) {
                    form.setContactUsDescLangFlag(true);
                    form.setContactUsDescLang(contactUsLanguage.getContactUsDesc());
                }
                break;
            }
        }
    }
    initSearchInfo(form, site.getSiteId());
    FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
    ActionForward actionForward = actionMapping.findForward("success");
    return actionForward;
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void doRemove(final EntityManagerFactory emf, Person[][] people) {
    for (final Person[] element2 : people) {
        for (Person person : element2) {
            final EntityManager em = this.open(emf);

            person = em.find(Person.class, person.getId());

            this.doBenchmarkRemove(em, person);
        }/*from ww w  .  ja v  a  2s .  com*/
    }
}

From source file:com.enioka.jqm.tools.Loader.java

private void runPayload() {
    // Set thread name
    Thread.currentThread().setName(threadName);

    // One log per launch?
    if (System.out instanceof MultiplexPrintStream) {
        String fileName = StringUtils.leftPad("" + this.job.getId(), 10, "0");
        MultiplexPrintStream mps = (MultiplexPrintStream) System.out;
        mps.registerThread(String.valueOf(fileName + ".stdout.log"));
        mps = (MultiplexPrintStream) System.err;
        mps.registerThread(String.valueOf(fileName + ".stderr.log"));
    }/*ww  w  . j av  a  2 s . co  m*/

    EntityManager em = null;
    final Map<String, String> params;
    final JarClassLoader jobClassLoader;

    // Block needing the database
    try {
        em = Helpers.getNewEm();

        // Refresh entities from the current EM
        this.job = em.find(JobInstance.class, job.getId());
        this.node = em.find(Node.class, job.getNode().getId());

        // Log
        this.resultStatus = State.SUBMITTED;
        jqmlogger.debug("A loader/runner thread has just started for Job Instance " + job.getId() + ". Jar is: "
                + job.getJd().getJarPath() + " - class is: " + job.getJd().getJavaClassName());

        // Disabled
        if (!this.job.getJd().isEnabled()) {
            jqmlogger.info("Job Instance " + job.getId()
                    + " will actually not truly run as its Job Definition is disabled");
            em.getTransaction().begin();
            this.job.setProgress(-1);
            em.getTransaction().commit();
            resultStatus = State.ENDED;
            endOfRun();
            return;
        }

        // Parameters
        params = new HashMap<String, String>();
        for (RuntimeParameter jp : em
                .createQuery("SELECT p FROM RuntimeParameter p WHERE p.ji = :i", RuntimeParameter.class)
                .setParameter("i", job.getId()).getResultList()) {
            jqmlogger.trace("Parameter " + jp.getKey() + " - " + jp.getValue());
            params.put(jp.getKey(), jp.getValue());
        }

        // Update of the job status, dates & co
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (!job.getState().equals(State.KILLED)) {
            // Use a query to avoid locks on FK checks (with setters, every field is updated!)
            em.createQuery(
                    "UPDATE JobInstance j SET j.executionDate = current_timestamp(), state = 'RUNNING' WHERE j.id = :i")
                    .setParameter("i", job.getId()).executeUpdate();
        }
        em.getTransaction().commit();

        jobClassLoader = this.clm.getClassloader(job, em);
    } catch (JqmPayloadException e) {
        jqmlogger.warn("Could not resolve CLASSPATH for job " + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (MalformedURLException e) {
        jqmlogger.warn("The JAR file path specified in Job Definition is incorrect "
                + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (RuntimeException e) {
        firstBlockDbFailureAnalysis(e);
        return;
    } finally {
        Helpers.closeQuietly(em);
    }

    // Class loader switch
    classLoaderToRestoreAtEnd = Thread.currentThread().getContextClassLoader();
    try {
        // Switch
        jqmlogger.trace("Setting class loader");
        Thread.currentThread().setContextClassLoader(jobClassLoader);
        jqmlogger.trace("Class Loader was set correctly");
    } catch (Exception e) {
        jqmlogger.error("Could not switch classloaders", e);
        this.resultStatus = State.CRASHED;
        endOfRun();
        return;
    }

    // Go! (launches the main function in the startup class designated in the manifest)
    try {
        jobClassLoader.launchJar(job, params);
        this.resultStatus = State.ENDED;
    } catch (JqmKillException e) {
        jqmlogger.info("Job instance  " + job.getId() + " has been killed.");
        this.resultStatus = State.KILLED;
    } catch (Exception e) {
        jqmlogger.info("Job instance " + job.getId() + " has crashed. Exception was:", e);
        this.resultStatus = State.CRASHED;
    }

    // Job instance has now ended its run
    try {
        endOfRun();
    } catch (Exception e) {
        jqmlogger.error("An error occurred while finalizing the job instance.", e);
    }

    jqmlogger.debug("End of loader for JobInstance " + this.job.getId() + ". Thread will now end");
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public UserSession saveUserSession(UserSession userSession) {
    logger.info("Will userSession = " + userSession.getUsername());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from w w w .  j  a v a 2 s  . co m

    FStoreUser u = entityManager.find(FStoreUser.class, userSession.getUser().getId());
    userSession.setUser(u);

    logger.info("Will userSession = " + u.toString());

    entityManager.persist(u);
    entityManager.persist(userSession);
    entityManager.flush();
    entityTransaction.commit();

    return userSession;

}

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

/**
 * Removes old configlets from the {@link #configlets} map.
 *
 * Checks for every <tt>Configlet</tt> in the map, if still exists in the database.
 * If not, the map entry will be removed and <tt>shutdown()</tt> invoked on the old configlet entry. 
 *
 * @param emParam an EntityManager managing <tt>Configlet</tt>s
 *///w  w w. ja v  a  2 s .  co  m
@SuppressWarnings({ "SuspiciousMethodCalls" })
private synchronized void shutdownOldConfiglets(final EntityManager emParam) {
    Set<String> set = configlets.keySet();
    Object[] keys = set.toArray();
    for (Object name : keys) {
        emParam.getTransaction().begin();
        try {
            if (emParam.find(ConfigletState.class, name) == null) {
                Configlet let = configlets.get(name);
                configlets.remove(name);
                let.shutdown();
            }
        } catch (RuntimeException e) {
            logger.warn(e);
        } finally {
            if (emParam.getTransaction().isActive())
                emParam.getTransaction().commit();
        }
    }
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void doBenchmarkFind(final EntityManagerFactory emf, Person[][] people) {
    for (int i = 0; i < (people.length / 2); i++) {
        for (final Person person : people[i]) {
            final EntityManager em = this.open(emf);

            final Person person2 = em.find(Person.class, person.getId());
            person2.getPhones().size();/*from  w w w.java  2 s. c o m*/

            this.close(em);
        }
    }
}

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

@GET
@Produces(MediaType.APPLICATION_JSON)//from w ww  . j a  v a2 s  .c  o  m
@Path("{id}/details")
public Response getFeedDetails(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;
    User user;
    Feed feed;
    FeedData feedData;
    FeedDetails details;

    em = HibernateUtil.getEntityManager();

    try {
        user = (User) context.getUserPrincipal();
        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();
        }

        feedData = feed.getData();
        details = new FeedDetails();
        details.setDescription(feedData.getDescription());
        details.setWebsite(feedData.getWebsiteUrl());
        details.setLastFetchError(feedData.getLastError());
        details.setTitle(feedData.getTitle());

        return Response.ok(details).build();
    } finally {
        em.close();
    }
}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

private Organization getOrganization(Integer id) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    return (Organization) em.find(Organization.class, id);
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void doUpdate(final EntityManagerFactory emf, final Person[][] people) {
    for (final Person[] persons : people) {
        for (final Person person : persons) {
            final EntityManager em = this.open(emf);

            this.doBenchmarkUpdate(em, em.find(Person.class, person.getId()));
        }/*from  ww  w  .j ava  2  s  . co  m*/
    }
}