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:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testPersist() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager em = emf.createEntityManager();
    PObject pc = new PObject("XYZ");
    em.getTransaction().begin();/*from   ww  w .  j  a  v a 2  s  .  c o m*/
    em.persist(pc);
    em.getTransaction().commit();
    Object oid = pc.getId();

    em.clear();
    // After clean the instance must not be in L1 cache
    assertFalse(em.contains(pc));
    // But it must be found in L2 cache by its OpenJPA identifier
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));

    PObject pc2 = em.find(PObject.class, oid);
    // After find(), the original instance is not in the L1 cache
    assertFalse(em.contains(pc));
    // After find(), the found instance is in the L1 cache
    assertTrue(em.contains(pc2));
    // The L2 cache must still hold the key   
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

/**
  */* www  . j av  a  2  s  . co  m*/
  */
public String authenticate(final String userID, final String credential) throws AuthenticationException {
    if (userID == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID));
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        // Create a principal for the userID
        Principal principal = new Principal() {
            public String getName() {
                return userID;
            }
        };

        if (!authManager.isValid(principal, credential)) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials"));
        } else {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, userID);
            if (publisher == null) {
                publisher = new Publisher();
                publisher.setAuthorizedName(userID);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(199);
                publisher.setMaxBusinesses(100);
                publisher.setMaxServicesPerBusiness(100);
                publisher.setMaxTmodels(100);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        }
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return userID;
}

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

public void edit(Persona persona) throws Exception {
    EntityManager em = null;
    try {/*from   w w w .j a v a2  s.c o m*/
        em = getEntityManager();
        em.getTransaction().begin();

        Persona personaAntigua = em.find(Persona.class, persona.getId());
        Hibernate.initialize(personaAntigua.getPersonaFirmasCollection());

        //quitar los personaTitulo que no existan en la nueva persona editada
        for (PersonaTitulo perTituloAntiguo : personaAntigua.getPersonaTitulosCollection()) {
            if (!persona.getPersonaTitulosCollection().contains(perTituloAntiguo)) {
                em.remove(perTituloAntiguo);
            }
        }
        //poner en null los ids negativos para que se puedan crear
        for (PersonaTitulo perTitulo : persona.getPersonaTitulosCollection()) {
            if (perTitulo.getId() != null && perTitulo.getId() < 0) {
                perTitulo.setId(null);
            }
            if (perTitulo.getPersona() == null) {
                perTitulo.setPersona(persona);
            }
            Titulo titulo = perTitulo.getTitulo();
            if (titulo.getId() == null || titulo.getId() < 0) {
                titulo.setId(null);
                em.persist(titulo);
            }
            if (perTitulo.getUniversidad().getId() == null || perTitulo.getUniversidad().getId() < 0) {
                perTitulo.getUniversidad().setId(null);
                em.persist(perTitulo.getUniversidad());
            }
            em.merge(perTitulo);
        }

        for (PersonaFirma perFirmaAntiguo : personaAntigua.getPersonaFirmasCollection()) {
            //revisar las firmas que estn en el antigua persona pero ya no en el nuevo editado,
            // por lo tanto si ya no estn en el nuevo editado, hay que borrar las relaciones PersonaFirma
            // pero solo si no tiene PersonaArticulo relacionado (significara que esa firma est actualmente 
            // siendo usada en un artculo, por lo tanto no de debe borrar)
            boolean firmaEnEditado = false;

            //primero revisar si la firma que existia antes de la persona, existe en el nuevo editado
            for (PersonaFirma perFirma : persona.getPersonaFirmasCollection()) {
                if (StringUtils.equalsIgnoreCase(perFirmaAntiguo.getFirma().getNombre(),
                        perFirma.getFirma().getNombre())) {
                    firmaEnEditado = true;
                    break;
                }
            }
            if (!firmaEnEditado) {
                //si es que la firma de la persona sin editar ya no existe en la persona editada, quitar la relacin PersonaFirma

                //primero verificar que la firma no sea usada en ninguna PersonaArticulo
                if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                    Firma firmaBorrar = null;
                    if (perFirmaAntiguo.getFirma().getPersonasFirmaCollection().size() == 1) {
                        //si la firma a borrar esta asignada a solo una persona (que sera la persona actual, variable: persona),
                        // colocarla a la variable para borrarla
                        //Siempre las firmas van a estar asignadas al menos a una persona, caso contrario deben ser borradas
                        //Las firmas de personas desconocidas estn ligadas a una persona: la persona con id=0
                        firmaBorrar = perFirmaAntiguo.getFirma();
                    }
                    //borrar la relacin PersonaFirma
                    em.remove(perFirmaAntiguo);
                    if (firmaBorrar != null) {
                        //borrar la firma solo si estaba asignada a una sola persona
                        firmaBorrar.getPersonasFirmaCollection().clear();
                        em.remove(firmaBorrar);
                    }
                }
            }
            /*
            if (!persona.getPersonaFirmasCollection().contains(perFirmaAntiguo)) {
            if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                em.remove(em);
            }
            }*/
        }
        guardarPersonaFirma(em, persona);

        em.merge(persona);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:streaming.StreamingTest.java

public void listerFilmParGenreOK() {
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    for (Film f : em.find(Genre.class, 1L).getListeFilmsParGenre()) {
        System.out.println(f.getTitre());
    }/*from   ww w .  j  a v a2  s  . c om*/
}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

@Override
public void deleteStoredQuery(final String queryName) throws ArtificerException {
    new HibernateUtil.HibernateTask<Void>() {
        @Override/*from w  ww  .  j a v  a  2  s.c o m*/
        protected Void doExecute(EntityManager entityManager) throws Exception {
            // Orphan removal is not honored by JPQL, so we need to manually delete using #remove.
            ArtificerStoredQuery storedQuery = entityManager.find(ArtificerStoredQuery.class, queryName);
            if (storedQuery == null) {
                throw ArtificerNotFoundException.storedQueryNotFound(queryName);
            }

            entityManager.remove(storedQuery);
            HibernateUtil.evict(ArtificerStoredQuery.class, storedQuery.getQueryName(), entityManager);

            return null;
        }
    }.execute();
}

From source file:org.sigmah.server.servlet.exporter.models.ProjectModelHandler.java

@Override
public String exportModel(OutputStream outputStream, String identifier, EntityManager em) throws Exception {

    String name = "";

    if (identifier == null) {
        throw new ExportException("The identifier is missing.");
    }//from w  ww.ja va2s.c  om

    final Integer projectModelId = Integer.parseInt(identifier);

    final ProjectModel hibernateModel = em.find(ProjectModel.class, projectModelId);

    if (hibernateModel == null)
        throw new ExportException("No project model is associated with the identifier '" + identifier + "'.");

    name = hibernateModel.getName();

    // Removing superfluous links
    hibernateModel.setVisibilities(null);

    // Stripping hibernate proxies from the model.
    final ProjectModel realModel = Realizer.realize(hibernateModel);

    // Serialization
    try {

        final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(realModel);

    } catch (Exception ex) {
        throw new Exception("An error occured while serializing the project model " + projectModelId, ex);
    }

    return name;
}

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

@GET
@Path("{id}/icon")
@Produces("image/png")
@PermitAll//from   ww w  .j av  a 2  s .  c o  m
public Response getFeedIcon(@Context ServletContext ctx, @PathParam("id") int feedId,
        @QueryParam("token") String tokenString) throws IOException {
    EntityManager em = HibernateUtil.getEntityManager();
    Token token;
    Feed feed;
    byte[] data;

    try {
        token = Token.loadToken(em, tokenString);

        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND).entity(emptyGif(ctx)).build();
        }
        if (!feed.getUser().equals(token.getUser())) {
            return Response.status(Response.Status.FORBIDDEN).entity(emptyGif(ctx)).build();
        }

        data = feed.getData().getIconData();
        if (data == null)
            data = emptyGif(ctx);

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

From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java

public Resolution save() {
    EntityManager em = Stripersist.getEntityManager();
    solrConfiguration.getIndexAttributes().clear();
    solrConfiguration.getResultAttributes().clear();
    for (int i = 0; i < indexAttributes.length; i++) {
        Long attributeId = indexAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getIndexAttributes().add(attribute);
    }//ww  w .  jav a  2s  .c om

    for (int i = 0; i < resultAttributes.length; i++) {
        Long attributeId = resultAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getResultAttributes().add(attribute);
    }
    em.persist(solrConfiguration);
    em.getTransaction().commit();

    return new ForwardResolution(EDIT_JSP);
}

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

public ActionForward translate(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();
    }/*from  w  w  w  .j  a v a2 s .  c o  m*/

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

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

    BingTranslate translator = new BingTranslate(form.getFromLocale(), form.getToLocale(), site);
    form.setContactUsNameLangFlag(true);
    form.setContactUsDescLangFlag(true);
    form.setContactUsNameLang(translator.translate(contactUs.getContactUsLanguage().getContactUsName()));
    form.setContactUsDescLang(translator.translate(contactUs.getContactUsLanguage().getContactUsDesc()));

    initSearchInfo(form, site.getSiteId());
    FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
    ActionForward actionForward = actionMapping.findForward("success");
    return actionForward;
}

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

/**
 * {@inheritDoc}//from   ww  w  . ja  v a  2 s.co  m
 */
@Override
public <T extends BaseEntity> T findById(Class<T> entity, Object primaryKey) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        return em.find(entity, primaryKey);
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}