Example usage for javax.persistence EntityManager contains

List of usage examples for javax.persistence EntityManager contains

Introduction

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

Prototype

public boolean contains(Object entity);

Source Link

Document

Check if the instance is a managed entity instance belonging to the current persistence context.

Usage

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

/**
 * Store object using an existing transaction.
 * @param obj the object to persist// w  w  w  . j  a  v a2 s .  c  om
 * @return the object persisted
 * @throws org.apache.roller.planet.PlanetException on any error
 */
public Object store(Object obj) throws PlanetException {
    EntityManager em = getEntityManager(true);
    if (!em.contains(obj)) {
        // If entity is not managed we can assume it is new
        em.persist(obj);
    }
    return obj;
}

From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java

@Override
@PortalTransactional//from   www.  ja v a2s  .c o  m
public void deleteAccount(ILocalAccountPerson account) {
    Validate.notNull(account, "definition can not be null");

    final EntityManager entityManager = this.getEntityManager();

    final ILocalAccountPerson persistentAccount;
    if (entityManager.contains(account)) {
        persistentAccount = account;
    } else {
        persistentAccount = entityManager.merge(account);
    }

    entityManager.remove(persistentAccount);
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return an attached entity if found, null otherwise
 *///from   w  w  w.  j a  v  a2  s.com
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
    final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
    MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
    temp.setMarketplaceRatingPK(marketplaceRatingPK);
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(temp)) {
        temp = entityManager.merge(temp);
        return temp;
    } else {
        final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(
                this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {
                    @Override
                    public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                        final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input
                                .createQuery(MarketplaceRatingImpl.class);
                        final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery
                                .from(MarketplaceRatingImpl.class);
                        Predicate conditionUser = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("userName"),
                                tempRatingPK.getUserName());
                        Predicate conditionPortlet = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("portletDefinition"),
                                tempRatingPK.getPortletDefinition());
                        Predicate allConditions = input.and(conditionPortlet, conditionUser);
                        criteriaQuery.where(allConditions);
                        return criteriaQuery;
                    }
                }));
        List<MarketplaceRatingImpl> results = query.getResultList();
        if (!results.isEmpty()) {
            return results.get(0);
        } else {
            return null;
        }
    }
}

From source file:fr.univrouen.poste.domain.User.java

@Transactional
public void remove() {
    EntityManager entityManager = entityManager();
    User user = this;
    if (!entityManager.contains(this)) {
        user = User.findUser(this.getId());
    }/*from   w ww .  j a  v  a  2s . c o m*/

    // candidat
    List<GalaxieEntry> galaxieEntries = GalaxieEntry.findGalaxieEntrysByCandidat(user).getResultList();
    for (GalaxieEntry galaxieEntry : galaxieEntries) {
        galaxieEntry.remove();
    }
    List<PosteCandidature> candidatures = PosteCandidature.findPosteCandidaturesByCandidat(user)
            .getResultList();
    for (PosteCandidature candidature : candidatures) {
        candidature.remove();
    }

    // membre
    List<CommissionEntry> commissionEntries = CommissionEntry.findCommissionEntrysByMembre(user)
            .getResultList();
    for (CommissionEntry commissionEntry : commissionEntries) {
        commissionEntry.getPoste().getMembres().remove(user);
        commissionEntry.remove();
    }
    Set<PosteAPourvoir> postes = user.getPostes();
    if (postes != null) {
        for (PosteAPourvoir poste : postes) {
            poste.getMembres().remove(user);
        }
    }

    entityManager.remove(user);
}

From source file:org.springframework.batch.item.database.JpaItemWriter.java

/**
 * Do perform the actual write operation. This can be overridden in a
 * subclass if necessary.//from   w w w . ja v  a  2 s. co m
 *
 * @param entityManager the EntityManager to use for the operation
 * @param items the list of items to use for the write
 */
protected void doWrite(EntityManager entityManager, List<? extends T> items) {

    if (logger.isDebugEnabled()) {
        logger.debug("Writing to JPA with " + items.size() + " items.");
    }

    if (!items.isEmpty()) {
        long mergeCount = 0;
        for (T item : items) {
            if (!entityManager.contains(item)) {
                entityManager.merge(item);
                mergeCount++;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(mergeCount + " entities merged.");
            logger.debug((items.size() - mergeCount) + " entities found in persistence context.");
        }
    }

}

From source file:org.synyx.hades.dao.orm.GenericJpaDao.java

public void delete(final T entity) {

    EntityManager em = getEntityManager();
    em.remove(em.contains(entity) ? entity : em.merge(entity));
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * /* w  ww  .  ja  v  a2  s.c om*/
 * @param obj
 *            object to remove
 * @return remove object
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public T remove(T obj) throws Exception {
    if (obj == null) {
        return null;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        T tmp = em.contains(obj) ? obj : em.merge(obj);
        em.remove(tmp);
        t.commit();
        return tmp;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * This method will either create a new rating or update an
 * existing rating/*from ww w  .j  av a2s .c  o m*/
 * 
 * @param  Must not be null
 * @return the attached entity
 * 
 */
@Override
@PortalTransactional
public IMarketplaceRating createOrUpdateRating(IMarketplaceRating marketplaceRatingImplementation) {
    Validate.notNull(marketplaceRatingImplementation, "MarketplaceRatingImpl must not be null");
    final EntityManager entityManager = this.getEntityManager();
    IMarketplaceRating temp = this.getRating(marketplaceRatingImplementation.getMarketplaceRatingPK());
    if (!entityManager.contains(marketplaceRatingImplementation) && temp != null) {
        //Entity is not managed and there is a rating for this portlet/user - update needed
        temp = entityManager.merge(marketplaceRatingImplementation);
    } else {
        //Entity is either already managed or doesn't exist - create needed
        temp = marketplaceRatingImplementation;
    }
    entityManager.persist(temp);
    return temp;
}

From source file:cz.fi.muni.pa165.daoImpl.TroopDAOImpl.java

@Override
public void removeTroop(Troop troop) throws IllegalArgumentException {
    if (troop == null) {
        throw new IllegalArgumentException("Troop can't be null.");
    }/*ww  w  .j  a v  a  2 s .  c o  m*/
    if (troop.getId() == null) {
        throw new IllegalArgumentException("Troop is not present in DB.");
    }
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Troop present = em.find(Troop.class, troop.getId());
    em.getTransaction().commit();

    if (present == null) {
        throw new IllegalArgumentException("Troop is not present in DB.");
    } else {
        em.getTransaction().begin();
        em.remove(em.contains(troop) ? troop : em.merge(troop));
        em.getTransaction().commit();
    }
    em.close();
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * /*  ww  w .  jav a2  s.c om*/
 * @param objs
 *            objects to remove
 * @return removed objects
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public Collection<T> remove(Collection<T> objs) throws Exception {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    Collection<T> res = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            T tmp = em.contains(obj) ? obj : em.merge(obj);
            em.remove(tmp);
            res.add(tmp);
        }
        t.commit();
        return res;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}