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.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy.java

/**
 * Retrieve object, no transaction needed.
 * @param clazz the class of object to retrieve
 * @param id the id of the object to retrieve
 * @return the object retrieved/*from  w w w  . j a  v  a  2 s. c  o  m*/
 * @throws WebloggerException on any error retrieving object
 */
public Object load(Class clazz, String id) throws WebloggerException {
    EntityManager em = getEntityManager(false);
    return em.find(clazz, id);
}

From source file:com.headissue.pigeon.survey.answer.AnswerHandler.java

public void receiveAnswer(Session _session, AnswerParameter p) {
    checkPreCondition(_session, p);/* w  w  w  .  j a va 2s . co m*/
    EntityManager _manager = factory.createEntityManager();
    try {
        _manager.getTransaction().begin();
        Survey _survey = _manager.find(Survey.class, p.getSurveyId());
        checkNotNull(_survey, "unknown survey '%s'", p.getSurveyId());
        int _mapId = userMapService.getUserMapId(_session);
        final UserMap map;
        if (_mapId <= 0 || _mapId != p.getMapId()) {
            map = createUserMap(_survey, p, _manager);
        } else {
            map = loadUserMap(_survey, _mapId, _manager);
        }
        checkNotNull(map, "unknown user map for survey '%s'", p.getSurveyId());
        Date _timestamp = new Date(p.getTimestamp());
        for (UserAnswerValue _value : p.getValues().getAnswers()) {
            Question _question = findQuestion(_survey, _value.getQuestionId());
            if (_question == null) {
                continue;
            }
            storeAnswer(_survey, _question, map, _value, _manager, _timestamp);
        }
        _manager.getTransaction().commit();
        checkTrue(map.getId() != 0, "user map can not created for survey '%s'", p.getSurveyId());
        userMapService.setUserMapId(_session, map.getId());
    } catch (Exception e) {
        LogUtils.warn(log, "receiveAnswer: processing is failed");
        throw new AnswerException("processing is failed", e);
    } finally {
        _manager.close();
    }
}

From source file:facades.PersonFacadeDB.java

@Override
public String getPerson(Integer id) throws NotFoundException {
    String result = "";
    //get person with this id from DB
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();// w  w  w  .j  a  va 2 s  .c  o m
    try {
        Person p = em.find(Person.class, id);

        result = om.writeValueAsString(p);
        //            Query query = em.createNamedQuery("Person.findById").setParameter("id", id);
        //            List<Person> people = query.getResultList();

        //result = gson.toJson(people.get(0));
        //result = om.writeValueAsString(people.get(0));
    } catch (Exception e) {
        throw new NotFoundException("No person exists for the given id");
    } finally {
        em.close();
    }
    return result;
}

From source file:org.apache.roller.planet.business.jpa.JPAPersistenceStrategy.java

/**
 * Retrieve object, no transaction needed.
 * @param clazz the class of object to retrieve
 * @param id the id of the object to retrieve
 * @return the object retrieved/*from   w ww . j  a  va2s  . c  om*/
 * @throws PlanetException on any error retrieving object
 */
public Object load(Class clazz, String id) throws PlanetException {
    EntityManager em = getEntityManager(false);
    return em.find(clazz, id);
}

From source file:fr.amapj.service.services.authentification.PasswordManager.java

/**
 * Permet de changer le password//from   w  w w  .j  ava2s. co m
 * Ceci est fait dans une transaction en ecriture  
 */
@DbWrite
public boolean setUserPassword(final Long userId, final String clearPassword) {
    EntityManager em = TransactionHelper.getEm();

    Utilisateur r = em.find(Utilisateur.class, userId);
    if (r == null) {
        logger.warn("Impossible de retrouver l'utilisateur avec l'id " + userId);
        return false;
    }

    if (r.getSalt() == null) {
        r.setSalt(fromByteArray(passwordEncryptionService.generateSalt()));
    }

    byte[] salt = toByteArray(r.getSalt());
    byte[] encryptedPass = passwordEncryptionService.getEncryptedPassword(clearPassword, salt);
    r.setPassword(fromByteArray(encryptedPass));

    // A chaque changement du mot de passe on supprime la r initilisation par mail
    r.setResetPasswordDate(null);
    r.setResetPasswordSalt(null);

    return true;

}

From source file:org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy.java

/**
 * Remove object from persistence storage.
 * @param clazz the class of object to remove
 * @param id the id of the object to remove
 * @throws WebloggerException on any error deleting object
 *//*w  w w .jav  a  2 s .  c  om*/
public void remove(Class clazz, String id) throws WebloggerException {
    EntityManager em = getEntityManager(true);
    Object po = em.find(clazz, id);
    em.remove(po);
}

From source file:org.apache.roller.planet.business.jpa.JPAPersistenceStrategy.java

/**
 * Remove object from persistence storage.
 * @param clazz the class of object to remove
 * @param id the id of the object to remove
 * @throws PlanetException on any error deleting object
 *///  ww  w. ja v a2  s .  com
public void remove(Class clazz, String id) throws PlanetException {
    EntityManager em = getEntityManager(true);
    Object po = em.find(clazz, id);
    em.remove(po);
}

From source file:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreAssignedAuteurEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();/*from w  ww  .j a v a 2  s.c  o m*/

    LivreEntry livre = em.find(LivreEntry.class, e.getIsbn());
    AuteurEntry auteur = em.find(AuteurEntry.class, e.getAuteurId());

    livre.getAuteurs().add(auteur);
    auteur.getLivres().add(livre);

    t.commit();
}

From source file:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreUnassignedAuteurEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();/*from ww w . j  a  va2s  .  c  o  m*/

    LivreEntry livre = em.find(LivreEntry.class, e.getIsbn());
    AuteurEntry auteur = em.find(AuteurEntry.class, e.getAuteurId());

    livre.getAuteurs().remove(auteur);
    auteur.getLivres().remove(livre);

    t.commit();
}

From source file:org.eclipse.jubula.client.core.persistence.NodePM.java

/**
 * Returns test cases that reference the test case given information. 
 * Only returns test cases that are <em>NOT</em> in the same project 
 * as the given test case./*from  w w w. j a va 2 s. c o m*/
 * This method opens a new session to gather the test cases and then closes
 * the session in order to prevent accidental DB commits for test cases
 * external to the current project.
 * Warning: the fetched ExecTestCases have no parent, because the database
 * doesn't know the parent.
 * 
 * @param specTcGuid GUID of the test case being reused.
 * @param parentProjectId ID of the parent project of the test case being
 *                        reused.
 * @return all test cases that reference the test case with the given
 *         information, provided that the cases are <em>NOT</em> in the 
 *         same project.
 * @see getInternalExecTestCases
 * @see getAllExecTestCases
 */
public static List<IExecTestCasePO> getExternalExecTestCases(String specTcGuid, long parentProjectId)
        throws JBException {

    // a SpecTC with guid == null can't be reused
    if (specTcGuid == null) {
        return new ArrayList<IExecTestCasePO>(0);
    }

    EntityManager s = Persistor.instance().openSession();

    try {
        EntityTransaction tx = Persistor.instance().getTransaction(s);

        IProjectPO parentProject = s.find(NodeMaker.getProjectPOClass(), parentProjectId);

        if (parentProject == null) {
            String error = Messages.ParentProjectDoesNotExistWithID + StringConstants.COLON
                    + StringConstants.SPACE + parentProjectId;
            log.error(error);
            throw new JBException(error, MessageIDs.E_DATABASE_GENERAL);
        }

        List<Long> projectsThatReuse = ProjectPM.findIdsThatReuse(parentProject.getGuid(),
                parentProject.getMajorProjectVersion(), parentProject.getMinorProjectVersion());

        List<IExecTestCasePO> tcList = getExecTestCasesFor(specTcGuid, projectsThatReuse, s);

        Persistor.instance().commitTransaction(s, tx);

        return tcList;

    } finally {
        Persistor.instance().dropSessionWithoutLockRelease(s);
    }
}