Java Code Examples for javax.persistence.EntityManager#remove()

The following examples show how to use javax.persistence.EntityManager#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserTokenDAO.java    From peer-os with Apache License 2.0 6 votes vote down vote up
void remove( final String id )
{
    EntityManager em = daoManager.getEntityManagerFromFactory();
    try
    {
        daoManager.startTransaction( em );
        UserTokenEntity item = em.find( UserTokenEntity.class, id );
        em.remove( item );
        daoManager.commitTransaction( em );
    }
    catch ( Exception e )
    {
        daoManager.rollBackTransaction( em );
        logger.error( "**** Error in UserTokenDAO:", e );
    }
    finally
    {
        daoManager.closeEntityManager( em );
    }
}
 
Example 2
Source File: JPAWorkItemHandlerTest.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
@Test
public void createOnProcessTest() throws Exception {
    String DESC = "Table";
    Product p = new Product(DESC,
                            10f);
    startJPAWIHProcess(JPAWorkItemHandler.CREATE_ACTION,
                       p);
    UserTransaction ut = getUserTransaction();
    ut.begin();
    EntityManager em = emf.createEntityManager();
    TypedQuery<Product> products = em.createQuery("select p from Product p where p.description = :desc",
                                                  Product.class);
    products.setParameter("desc",
                          DESC);
    List<Product> resultList = products.getResultList();
    Product result = resultList.iterator().next();
    assertEquals(DESC,
                 result.getDescription());
    em.remove(result);
    em.flush();
    em.close();
    ut.commit();
}
 
Example 3
Source File: JpaKubernetesRuntimeStateCache.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Transactional(rollbackOn = {RuntimeException.class, ServerException.class})
protected void doRemove(RuntimeIdentity runtimeIdentity) throws ServerException {
  EntityManager em = managerProvider.get();

  KubernetesRuntimeState runtime =
      em.find(KubernetesRuntimeState.class, runtimeIdentity.getWorkspaceId());

  if (runtime != null) {
    eventService
        .publish(
            new BeforeKubernetesRuntimeStateRemovedEvent(new KubernetesRuntimeState(runtime)))
        .propagateException();

    em.remove(runtime);
  }
}
 
Example 4
Source File: PeerDataService.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void remove( final String id )
{
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();
        PeerData item = em.find( PeerData.class, id );
        em.remove( item );
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOG.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
}
 
Example 5
Source File: DeleteIT.java    From bookapp-cqrs with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {

	EntityManager em = Persistence.createEntityManagerFactory(
			"ch.bfh.swos.bookapp.book.domain").createEntityManager();

	Query q = em.createQuery("select a from Author a");
	@SuppressWarnings("unchecked")
	List<Author> foundAuthors = q.getResultList();
	Author firstAuthor = foundAuthors.get(0);

	// Write access needs a transaction
	em.getTransaction().begin();
	em.remove(firstAuthor);
	em.getTransaction().commit();
}
 
Example 6
Source File: ConfigDataServiceImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteConfig( final String peerId )
{
    EntityManager em = daoManager.getEntityManagerFromFactory();

    try
    {
        daoManager.startTransaction( em );
        ConfigEntity entity = em.find( ConfigEntity.class, peerId );
        em.remove( entity );
        em.flush();
        daoManager.commitTransaction( em );
    }
    catch ( Exception ex )
    {
        daoManager.rollBackTransaction( em );
        LOG.error( "ConfigDataService deleteOperation: {}", ex.getMessage() );
    }
    finally
    {
        daoManager.closeEntityManager( em );
    }
}
 
Example 7
Source File: MultiuserPostgresqlTckModule.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void removeAll() throws TckRepositoryException {
  uow.begin();
  final EntityManager manager = managerProvider.get();
  try {
    manager.getTransaction().begin();

    for (int i = createdOrganizations.size() - 1; i > -1; i--) {
      // The query 'DELETE FROM ....' won't be correct as it will ignore orphanRemoval
      // and may also ignore some configuration options, while EntityManager#remove won't
      try {
        final OrganizationImpl organizationToRemove =
            manager
                .createQuery(
                    "SELECT o FROM Organization o " + "WHERE o.id = :id",
                    OrganizationImpl.class)
                .setParameter("id", createdOrganizations.get(i).getId())
                .getSingleResult();
        manager.remove(organizationToRemove);
      } catch (NoResultException ignored) {
        // it is already removed
      }
    }
    createdOrganizations.clear();

    manager.getTransaction().commit();
  } catch (RuntimeException x) {
    if (manager.getTransaction().isActive()) {
      manager.getTransaction().rollback();
    }
    throw new TckRepositoryException(x.getLocalizedMessage(), x);
  } finally {
    uow.end();
  }

  // remove all objects that was created in tests
  super.removeAll();
}
 
Example 8
Source File: JpaInviteDao.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
protected void doRemove(String domain, String instance, String email) {
  try {
    InviteImpl invite = getEntity(domain, instance, email);
    final EntityManager manager = managerProvider.get();
    manager.remove(invite);
    manager.flush();
  } catch (NotFoundException e) {
    // invite is already removed
  }
}
 
Example 9
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void testDeleteViaRemove(final EntityManagerFactory emf) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.remove(em.find(Pokemon.class, 3));
    em.remove(em.find(Pokemon.class, 248));
    em.remove(em.find(Pokemon.class, 242));
    transaction.commit();
    em.close();

    assertRegionStats(new Counts(0, 3, 0, 4), Pokemon.class.getName(), stats);

    stats = getStatistics(emf);

    em = emf.createEntityManager();
    transaction = em.getTransaction();
    transaction.begin();
    if (em.find(Pokemon.class, 3) != null
            || em.find(Pokemon.class, 248) != null
            || em.find(Pokemon.class, 242) != null) {
        throw new RuntimeException("Pokemons should have been deleted");
    }

    transaction.commit();
    em.close();

    assertRegionStats(new Counts(0, 0, 3, 4), Pokemon.class.getName(), stats);
}
 
Example 10
Source File: ActionDelete.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		Folder folder = emc.find(id, Folder.class);
		if (null == folder) {
			throw new ExceptionFolderNotExist(id);
		}
		if (!StringUtils.equalsIgnoreCase(effectivePerson.getDistinguishedName(), folder.getPerson())) {
			throw new ExceptionAccessDenied(effectivePerson.getName());
		}
		List<String> ids = new ArrayList<>();
		ids.add(folder.getId());
		ids.addAll(business.folder().listSubNested(folder.getId()));
		for (int i = ids.size() - 1; i >= 0; i--) {
			List<Attachment> attachments = emc.list(Attachment.class,
					business.attachment().listWithFolder(ids.get(i)));
			for (Attachment att : attachments) {
				StorageMapping mapping = ThisApplication.context().storageMappings().get(Attachment.class,
						att.getStorage());
				att.deleteContent(mapping);
				EntityManager em = emc.beginTransaction(Attachment.class);
				em.remove(att);
				em.getTransaction().commit();
			}
			EntityManager m = emc.beginTransaction(Folder.class);
			emc.delete(Folder.class, ids.get(i));
			m.getTransaction().commit();
		}
		Wo wo = new Wo();
		wo.setValue(true);
		result.setData(wo);
		return result;
	}
}
 
Example 11
Source File: MultiuserJpaWorkspaceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional(rollbackOn = {RuntimeException.class, ServerException.class})
protected Optional<WorkspaceImpl> doRemove(String id) throws ServerException {
  final WorkspaceImpl workspace = managerProvider.get().find(WorkspaceImpl.class, id);
  if (workspace == null) {
    return Optional.empty();
  }
  final EntityManager manager = managerProvider.get();
  eventService
      .publish(new BeforeWorkspaceRemovedEvent(new WorkspaceImpl(workspace)))
      .propagateException();
  manager.remove(workspace);
  manager.flush();
  return Optional.of(workspace);
}
 
Example 12
Source File: ServiceInstance.java    From development with Apache License 2.0 5 votes vote down vote up
void removeParams(HashMap<String, Setting> parameters, EntityManager em) {

        List<InstanceParameter> paramsToRemove = new ArrayList<>();
        List<InstanceParameter> params = this.getInstanceParameters();

        if (parameters != null) {
            for (InstanceParameter ip : this.getInstanceParameters()) {
                if (!parameters.containsKey(ip.getParameterKey())) {
                    paramsToRemove.add(ip);
                    em.remove(ip);
                }
            }
        }
        params.removeAll(paramsToRemove);
    }
 
Example 13
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Place place = null;
  try {
    place = mgr.find(Place.class, id);
    mgr.remove(place);
  } finally {
    mgr.close();
  }
}
 
Example 14
Source File: QueriesWithAssociationsTest.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void removeEntities() throws Exception {
	EntityManager em = getFactory().createEntityManager();
	for ( Class<?> each : getAnnotatedClasses() ) {
		em.getTransaction().begin();
		List<?> entities = em.createQuery( "FROM " + each.getSimpleName() ).getResultList();
		for ( Object object : entities ) {
			em.remove( object );
		}
		em.getTransaction().commit();
	}
	em.close();
}
 
Example 15
Source File: TestPersistentLocalTimeAsString.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Test @Ignore // Joda Time Contrib does not support Hibernate 4 yet
public void testNanosWithJodaTime() {

    EntityManager manager = factory.createEntityManager();

    manager.getTransaction().begin();
    for (int i = 0; i < localTimes.length; i++) {
        manager.remove(manager.find(LocalTimeAsStringJdk8.class, Long.valueOf(i)));
    }
    manager.flush();
    manager.getTransaction().commit();

    manager.getTransaction().begin();

    LocalTimeAsStringJdk8 item = new LocalTimeAsStringJdk8();
    item.setId(1);
    item.setName("test_nanos1");
    item.setLocalTime(LocalTime.of(10, 10, 10, 111444444));

    manager.persist(item);
    manager.flush();

    manager.getTransaction().commit();

    manager.close();

    manager = factory.createEntityManager();

    LocalTimeAsStringJoda jodaItem = manager.find(LocalTimeAsStringJoda.class, Long.valueOf(1));

    assertNotNull(jodaItem);
    assertEquals(1, jodaItem.getId());
    assertEquals("test_nanos1", jodaItem.getName());
    assertEquals(new org.joda.time.LocalTime(10, 10, 10, 111), jodaItem.getLocalTime());

    manager.close();

    manager = factory.createEntityManager();

    item = manager.find(LocalTimeAsStringJdk8.class, Long.valueOf(1));

    assertNotNull(item);
    assertEquals(1, item.getId());
    assertEquals("test_nanos1", item.getName());
    assertEquals(LocalTime.of(10, 10, 10, 111444444), item.getLocalTime());

    manager.close();
}
 
Example 16
Source File: JPADAO.java    From rome with Apache License 2.0 4 votes vote down vote up
@Override
public List<? extends Subscriber> subscribersForTopic(final String topic) {
    final LinkedList<JPASubscriber> result = new LinkedList<JPASubscriber>();
    final EntityManager em = factory.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    tx.begin();

    final Query query = em.createNamedQuery("Subcriber.forTopic");
    query.setParameter("topic", topic);

    try {
        @SuppressWarnings("unchecked")
        final List<JPASubscriber> subscribers = query.getResultList();
        for (final JPASubscriber subscriber : subscribers) {
            if (subscriber.getLeaseSeconds() == -1) {
                result.add(subscriber);
                continue;
            }

            if (subscriber.getSubscribedAt().getTime() < System.currentTimeMillis() - 1000 * subscriber.getLeaseSeconds()) {
                subscriber.setExpired(true);
            } else {
                result.add(subscriber);
            }

            if (subscriber.isExpired() && purgeExpired) {
                em.remove(subscriber);
            }
        }
    } catch (final NoResultException e) {
        tx.rollback();
        em.close();

        return result;
    }

    if (!tx.getRollbackOnly()) {
        tx.commit();
    } else {
        tx.rollback();
    }

    em.close();

    return result;
}
 
Example 17
Source File: AbstractJpaTest.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private static void clear(EntityManager em, List<?> list) {
    for (Object obj : list) {
        em.remove(obj);
    }
}
 
Example 18
Source File: TestPersistentLocalDateTime.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Test @Ignore // Nanos are not properly supported by JodaTime type
public void testNanosWithJodaTime() {

    EntityManager manager = factory.createEntityManager();

    manager.getTransaction().begin();
    for (int i = 0; i < localDateTimes.length; i++) {
        manager.remove(manager.find(LocalDateTimeJdk8.class, Long.valueOf(i)));
    }
    manager.flush();
    manager.getTransaction().commit();

    manager.getTransaction().begin();

    LocalDateTimeJdk8 item = new LocalDateTimeJdk8();
    item.setId(1);
    item.setName("test_nanos1");
    item.setLocalDateTime(LocalDateTime.of(2010, 8, 1, 10, 10, 10, 111444444));

    manager.persist(item);
    manager.flush();

    manager.getTransaction().commit();

    manager.close();

    manager = factory.createEntityManager();

    LocalDateTimeJoda jodaItem = manager.find(LocalDateTimeJoda.class, Long.valueOf(1));

    assertNotNull(jodaItem);
    assertEquals(1, jodaItem.getId());
    assertEquals("test_nanos1", jodaItem.getName());
    assertEquals(new org.joda.time.LocalDateTime(2010, 8, 1, 10, 10, 10, 111), jodaItem.getLocalDateTime());

    manager.close();

    manager = factory.createEntityManager();

    item = manager.find(LocalDateTimeJdk8.class, Long.valueOf(1));

    assertNotNull(item);
    assertEquals(1, item.getId());
    assertEquals("test_nanos1", item.getName());
    assertEquals(LocalDateTime.of(2010, 8, 1, 10, 10, 10, 111444444), item.getLocalDateTime());

    manager.close();
}
 
Example 19
Source File: TestPersistentInstantAsMillisLong.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Test @Ignore // Joda Time Contrib does not support Hibernate 4 yet
public void testNanosWithJodaTime() {

    EntityManager manager = factory.createEntityManager();

    manager.getTransaction().begin();
    for (int i = 0; i < instants.length; i++) {
        manager.remove(manager.find(InstantAsMillisLongJdk8.class, Long.valueOf(i)));
    }
    manager.flush();
    manager.getTransaction().commit();

    manager.getTransaction().begin();

    InstantAsMillisLongJdk8 item = new InstantAsMillisLongJdk8();
    item.setId(1);
    item.setName("test_nanos1");
    item.setInstant(ZonedDateTime.of(LocalDateTime.of(2010, 8, 1, 10, 10, 10, 111444444), ZoneId.of("Z")).toInstant());

    manager.persist(item);
    manager.flush();

    manager.getTransaction().commit();

    manager.close();

    manager = factory.createEntityManager();

    InstantAsBigIntJoda jodaItem = manager.find(InstantAsBigIntJoda.class, Long.valueOf(1));

    assertNotNull(jodaItem);
    assertEquals(1, jodaItem.getId());
    assertEquals("test_nanos1", jodaItem.getName());
    assertEquals(new org.joda.time.DateTime(2010, 8, 1, 10, 10, 10, 111, DateTimeZone.UTC).toInstant(), jodaItem.getInstant());

    manager.close();

    manager = factory.createEntityManager();

    item = manager.find(InstantAsMillisLongJdk8.class, Long.valueOf(1));

    assertNotNull(item);
    assertEquals(1, item.getId());
    assertEquals("test_nanos1", item.getName());
    assertEquals(ZonedDateTime.of(LocalDateTime.of(2010, 8, 1, 10, 10, 10, 111000000), ZoneId.of("Z")).toInstant(), item.getInstant());

    manager.close();
}
 
Example 20
Source File: SharedEntityManagerCreatorTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnRemove() {
	EntityManagerFactory emf = mock(EntityManagerFactory.class);
	EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
	em.remove(new Object());
}