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:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBag findBag(final long bagId) {
    final EmCallback<ProposalBag> emCallback = new EmCallback<ProposalBag>(this.getEmf()) {

        @Override// w  w w .ja v  a2s . c om
        protected ProposalBag executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final ProposalBag bag = em.find(ProposalBag.class, bagId);
            return bag;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public T update(T entity) throws ServiceException {
    try {// w w w. j  av  a2s . c  o  m
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();
        T loadedObject = entityManager.find(getObjectClass(), getObjectId(entity));
        T mergedEntity = merge(loadedObject, entity);
        T updatedEntity = entityManager.merge(mergedEntity);
        commitTransaction();
        return updatedEntity;
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't update object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public void deleteById(Serializable id) throws ServiceException {
    try {/*from   w  ww  .ja va2  s .co m*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();
        Object loadedEntity = entityManager.find(getObjectClass(), id);
        if (loadedEntity == null) {
            throw new ServiceException("Entity referenced by id " + id + " does not exist");
        }
        entityManager.remove(loadedEntity);
        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't delete object", e);
    } finally {
        closeEntityManager();
    }
}

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

/**
 * Get a single list.//www  .  j a v a 2 s  .com
 * @param _groupId The id of the group, containing the list.
 *     
 */
@GET
@TokenSecured
@Path("{listuuid}")
@Produces({ "application/json" })
public Response getList(@PathParam("groupid") int _groupId, @PathParam("listuuid") String _listUUID)
        throws Exception {
    UUID listUUID;
    try {
        listUUID = UUID.fromString(_listUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    IListController listController = ControllerFactory.getListController(manager);

    ShoppingList foundList = listController.findByGroupAndUUID(group, listUUID);
    if (foundList == null) {
        if (listController.findDeletedByGroupAndUUID(group, listUUID) == null) {
            manager.close();
            return ResponseFactory
                    .generateNotFound(new Error().withMessage("The requested " + "list was not found."));
        }
        manager.close();
        return ResponseFactory.generateGone(new Error().withMessage("The requested list was " + "deleted."));
    }

    ListInfo rtn = new ListInfo();
    rtn.setUUID(foundList.getUUID());
    rtn.setName(foundList.getName());
    if (foundList.getCategory() != null)
        rtn.setCategoryUUID(foundList.getCategory().getUUID());
    rtn.setLastChanged(Date.from(foundList.getUpdated()));
    rtn.setDeleted(false);

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Returns a single ingredient.//from  w  w w . ja v  a 2s  . c om
 * @param _groupId The id of the group containing the ingredient.
 * @param _entryUUID The uuid of the ingredient itself.
 */
@GET
@TokenSecured
@Path("{entryuuid}")
@Produces({ "application/json" })
public Response getIngredient(@PathParam("groupid") int _groupId, @PathParam("entryuuid") String _entryUUID)
        throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_entryUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    IIngredientController ingredientController = ControllerFactory.getIngredientController(manager);

    Ingredient foundIngredient = ingredientController.findByGroupAndUUID(group, toFind);
    if (foundIngredient == null) {
        if (ingredientController.findDeletedByGroupAndUUID(group, toFind) != null) {
            manager.close();
            return ResponseFactory
                    .generateGone(new Error().withMessage("The requested " + "ingredient has been deleted."));
        }
        manager.close();
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The requested " + "ingredient was not found."));
    }
    manager.close();

    IngredientInfo rtn = new IngredientInfo().withDeleted(false);
    rtn.setUUID(foundIngredient.getUUID());
    rtn.setProductUUID(foundIngredient.getProduct().getUUID());
    rtn.setRecipeUUID(foundIngredient.getRecipe().getUUID());
    rtn.setAmount(foundIngredient.getAmount());
    rtn.setLastChanged(Date.from(foundIngredient.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Returns a single ingredient./*from   ww w . j  a v  a2 s.c  o  m*/
 * @param _groupId The id of the group containing the tagged product.
 * @param _taggedProductUUID The uuid of the tagged product itself.
 */
@GET
@TokenSecured
@Path("{tpuuid}")
@Produces({ "application/json" })
public Response getTaggedProduct(@PathParam("groupid") int _groupId,
        @PathParam("tpuuid") String _taggedProductUUID) throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_taggedProductUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager);

    TaggedProduct foundTaggedProduct = taggedProductController.findByGroupAndUUID(group, toFind);
    if (foundTaggedProduct == null) {
        if (taggedProductController.findDeletedByGroupAndUUID(group, toFind) != null) {
            manager.close();
            return ResponseFactory.generateGone(
                    new Error().withMessage("The requested " + "tagged product has been deleted."));
        }
        manager.close();
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The requested " + "tagged product was not found."));
    }
    manager.close();

    TaggedProductInfo rtn = new TaggedProductInfo().withDeleted(false);
    rtn.setUUID(foundTaggedProduct.getUUID());
    rtn.setProductUUID(foundTaggedProduct.getProduct().getUUID());
    rtn.setTagUUID(foundTaggedProduct.getTag().getUUID());
    rtn.setLastChanged(Date.from(foundTaggedProduct.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * Internal method to find a RecordDao object by Record Id.
 * //from   ww  w .java  2s . c om
 * @param em
 *          the EntityManager to use
 * @param id
 *          the Id of the Record
 * @return the RecordDao object or null
 */
private RecordDao findRecordDao(final EntityManager em, final String id) {
    return em.find(RecordDao.class, RecordDao.getIdHash(id));
}

From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * /*from  w w  w .  j av  a2 s  .c  o  m*/
 * @return
 */
public double getBalance() throws Exception {
    if (!enableAccounting) {
        return 0.0;
    }

    if (balance == null) {
        Object identity = null;
        try {
            identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
            log.debug("Getting entity manager ......");
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            Account account = (Account) em.find(Account.class, organizationId);
            balance = account.getCreditBalance();
        } finally {
            log.debug("Closing entity manager .....");
            MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
        }

    }
    if (balance != null) {
        return balance.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    } else {
        return 0.0;
    }

}

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

/**
 * Get a list of units.// www  .  j  av a 2s.co  m
 * @param _groupId The id of the group containing the requested units.
 * @param _changedSince Requests only the elements that changed since the given date. ISO
 *                     8601 time e.g. 2016-01-19T11:54:07+01:00
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getUnits(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    List<Unit> resultUnits;
    List<DeletedObject> resultDeletedUnits;

    if (changedSince == null) {
        resultUnits = new ArrayList<Unit>(group.getUnits());
        TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery(
                "select do from " + "DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedUnitsQuery.setParameter("group", group);
        deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT);
        resultDeletedUnits = deletedUnitsQuery.getResultList();
    } else {
        TypedQuery<Unit> unitsQuery = manager.createQuery(
                "select u from Unit u where " + "u.group = :group and u.updated > :updated", Unit.class);
        unitsQuery.setParameter("group", group);
        unitsQuery.setParameter("updated", changedSince);
        resultUnits = unitsQuery.getResultList();

        TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery("select do from "
                + "DeletedObject do where do.group = :group and do.type = :type and " + "do.updated > :updated",
                DeletedObject.class);
        deletedUnitsQuery.setParameter("group", group);
        deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT);
        deletedUnitsQuery.setParameter("updated", changedSince);
        resultDeletedUnits = deletedUnitsQuery.getResultList();
    }
    manager.close();

    List<UnitInfo> rtn = new ArrayList<UnitInfo>(resultUnits.size() + resultDeletedUnits.size());
    for (Unit current : resultUnits) {
        UnitInfo info = new UnitInfo().withDeleted(false);
        info.setName(current.getName());
        info.setUUID(current.getUUID());
        info.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(info);
    }
    for (DeletedObject current : resultDeletedUnits) {
        UnitInfo info = new UnitInfo().withDeleted(true);
        info.setUUID(current.getUUID());
        info.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(info);
    }

    return ResponseFactory.generateOK(rtn);
}

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

JobManagerHandler(JobInstance ji, Map<String, String> prms) {
    p = new Properties();
    p.put("emf", Helpers.getEmf());

    EntityManager em = Helpers.getNewEm();
    this.ji = em.find(JobInstance.class, ji.getId());
    params = prms;//from w w w.ja va2  s  .co m

    defaultCon = em.createQuery("SELECT gp.value FROM GlobalParameter gp WHERE gp.key = 'defaultConnection'",
            String.class).getSingleResult();

    this.jd = this.ji.getJd();
    this.application = this.jd.getApplication();
    this.sessionId = this.ji.getSessionID();
    this.node = this.ji.getNode();
    this.node.getDlRepo();
    em.close();
}