javax.persistence.criteria.CriteriaDelete Java Examples

The following examples show how to use javax.persistence.criteria.CriteriaDelete. 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: HibernateCriteriaIntegrationTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenTargetItemPrice_whenCriteriaDelete_thenDeleteMatched() {

    int targetPrice = 1000;

    Session session = HibernateUtil.getHibernateSession();
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaDelete<Item> criteriaDelete = cb.createCriteriaDelete(Item.class);
    Root<Item> root = criteriaDelete.from(Item.class);
    criteriaDelete.where(cb.greaterThan(root.get("itemPrice"), targetPrice));

    Transaction transaction = session.beginTransaction();
    session.createQuery(criteriaDelete).executeUpdate();
    transaction.commit();

    List<Item> deletedItem = session.createQuery("FROM Item WHERE itemPrice > " + targetPrice, Item.class).list();
    assertTrue(deletedItem.isEmpty());

}
 
Example #2
Source File: TestCriteriaDelete.java    From HibernateTips with MIT License 7 votes vote down vote up
@Test
public void deleteBooks() {
	log.info("... deleteBooks ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	logBooks(em);
	
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaDelete<Book> delete = cb.createCriteriaDelete(Book.class);
	delete.from(Book.class);
	
	Query query = em.createQuery(delete);
	query.executeUpdate();

	logBooks(em);
	
	em.getTransaction().commit();
	em.close();
}
 
Example #3
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void delete() {
    final List<Long> checkedList = getCheckedList();
    for (Long id : checkedList) {
        checked.remove(id);
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<Post> q = cb.createCriteriaDelete(Post.class);
    Root<Post> root = q.from(Post.class);
    q.where(root.get("id").in(checkedList));

    int result = em.createQuery(q).executeUpdate();
    log.info("delete @" + result);
    load();
}
 
Example #4
Source File: AbstractQueryImpl.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
protected <E> javax.persistence.Query createDeleteQuery(EntityManager entityManager, QueryCriteria criteria, Class<E> dtoClass) {
    CriteriaDelete<E> deleteQuery = criteriaBuilder.createCriteriaDelete(dtoClass);
    Root<E> root = deleteQuery.from(dtoClass);
    deleteQuery.where(criteria.toQueryPredicates(root)
                              .toArray(new Predicate[0]));
    return entityManager.createQuery(deleteQuery);
}
 
Example #5
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public QueryImplementor createQuery(CriteriaDelete criteriaDelete) {
	checkOpen();
	try {
		return criteriaCompiler().compile( (CompilableCriteria) criteriaDelete );
	}
	catch ( RuntimeException e ) {
		throw exceptionConverter.convert( e );
	}
}
 
Example #6
Source File: MCRMetadataHistoryCommands.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@MCRCommand(syntax = "clear metadata history of base {0}",
    help = "clears metadata history of all objects with base id {0}")
public static void clearHistory(String baseId) {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<MCRMetaHistoryItem> delete = cb.createCriteriaDelete(MCRMetaHistoryItem.class);
    Root<MCRMetaHistoryItem> item = delete.from(MCRMetaHistoryItem.class);
    int rowsDeleted = em.createQuery(
        delete.where(
            cb.like(item.get(MCRMetaHistoryItem_.id).as(String.class), baseId + "_".replace("_", "$_") + '%', '$')))
        .executeUpdate();
    LogManager.getLogger().info("Deleted {} items in history of {}", rowsDeleted, baseId);
}
 
Example #7
Source File: MechanismEntityService.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 根据主文档删除,fdEntityKey可为空,不触发相关事件
 */
public <E extends IEntity> void deleteByEntity(Class<E> clazz,
		String fdEntityName, String fdEntityId, String fdEntityKey) {
	IteratorQueryTemplate<E> template = new IteratorQueryTemplate<>(
			entityManager, clazz).setFetchSize(1).setAutoFlush(false);
	IteratorQueryTemplate<E>.QueryIterator iterator = template
			.iterator(buildRequest(fdEntityName, fdEntityId, fdEntityKey));
	if (iterator.isEmpty()) {
		return;
	}
	CriteriaDelete<E> query = entityManager.getCriteriaBuilder()
			.createCriteriaDelete(clazz);
	query.where(query.from(clazz).get("fdId").in(iterator.getIds()));
	entityManager.createQuery(query).executeUpdate();
}
 
Example #8
Source File: CurrentVariantRollbackService.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the query to delete {@link com.box.l10n.mojito.entity.TMTextUnitCurrentVariant}s that will be rolled back
 *
 * @param tmId            ID of the TM the {@link TMTextUnitCurrentVariant}s to be rolled back should belong to
 * @param extraParameters Extra parameters to filter what to rollback
 * @return The delete query
 */
protected Query buildDeleteQuery(Long tmId, CurrentVariantRollbackParameters extraParameters) {

    logger.trace("Building the delete tmTextUnitCurrentVariants query");

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaDelete<TMTextUnitCurrentVariant> deleteCriteria = criteriaBuilder.createCriteriaDelete(TMTextUnitCurrentVariant.class);
    Root<TMTextUnitCurrentVariant> root = deleteCriteria.from(TMTextUnitCurrentVariant.class);

    Predicate whereClause = criteriaBuilder.conjunction();

    Predicate tmPredicate = criteriaBuilder.equal(root.get(TMTextUnitCurrentVariant_.tm), tmId);
    whereClause = criteriaBuilder.and(whereClause, tmPredicate);

    List<Long> localeIdsToRollback = extraParameters.getLocaleIds();
    if (localeIdsToRollback != null && !localeIdsToRollback.isEmpty()) {
        Predicate localesPredicate = criteriaBuilder.isTrue(root.get(TMTextUnitCurrentVariant_.locale).in(localeIdsToRollback));
        whereClause = criteriaBuilder.and(whereClause, localesPredicate);
    }

    List<Long> tmTextUnitIdsToRollback = extraParameters.getTmTextUnitIds();
    if (tmTextUnitIdsToRollback != null && !tmTextUnitIdsToRollback.isEmpty()) {
        Predicate tmTextUnitPredicate = criteriaBuilder.isTrue(root.get(TMTextUnitCurrentVariant_.tmTextUnit).in(tmTextUnitIdsToRollback));
        whereClause = criteriaBuilder.and(whereClause, tmTextUnitPredicate);
    }

    deleteCriteria.where(whereClause);

    return entityManager.createQuery(deleteCriteria);
}
 
Example #9
Source File: AbstractRepository.java    From batchers with Apache License 2.0 5 votes vote down vote up
public void deleteAll() {
    CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
    CriteriaDelete<E> criteriaDelete = criteriaBuilder.createCriteriaDelete(getEntityClass());

    criteriaDelete.from(getEntityClass());

    entityManager.createQuery(criteriaDelete).executeUpdate();
}
 
Example #10
Source File: NativeJpaQueryTranslator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public Query createDeletionQuery(Class queryClazz, TranslationContext criteria) {
       CriteriaDelete jpaQuery = entityManager.getCriteriaBuilder().createCriteriaDelete(queryClazz);

       if (!criteria.predicates.isEmpty()) {
           jpaQuery = jpaQuery.where(criteria.getCriteriaPredicate());
       }

       return entityManager.createQuery(jpaQuery);
   }
 
Example #11
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void delete() {
    final List<Long> checkedList = getCheckedList();
    for (Long id : checkedList) {
        checked.remove(id);
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<Post> q = cb.createCriteriaDelete(Post.class);
    Root<Post> root = q.from(Post.class);
    q.where(root.get("id").in(checkedList));

    int result = em.createQuery(q).executeUpdate();
    log.info("delete @" + result);
    load();
}
 
Example #12
Source File: MCRMetadataHistoryCommands.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@MCRCommand(syntax = "clear metadata history of id {0}",
    help = "clears metadata history of object/derivate with id {0}")
public static void clearSingleHistory(String mcrId) {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<MCRMetaHistoryItem> delete = cb.createCriteriaDelete(MCRMetaHistoryItem.class);
    Root<MCRMetaHistoryItem> item = delete.from(MCRMetaHistoryItem.class);
    int rowsDeleted = em.createQuery(
        delete.where(cb.equal(item.get(MCRMetaHistoryItem_.id).as(String.class), mcrId)))
        .executeUpdate();
    LogManager.getLogger().info("Deleted {} items in history of {}", rowsDeleted, mcrId);
}
 
Example #13
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void delete() {
    final List<Long> checkedList = getCheckedList();
    for (Long id : checkedList) {
        checked.remove(id);
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<Post> q = cb.createCriteriaDelete(Post.class);
    Root<Post> root = q.from(Post.class);
    q.where(root.get("id").in(checkedList));

    int result = em.createQuery(q).executeUpdate();
    log.info("delete @" + result);
    load();
}
 
Example #14
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void delete() {
    final List<Long> checkedList = getCheckedList();
    for (Long id : checkedList) {
        checked.remove(id);
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<Post> q = cb.createCriteriaDelete(Post.class);
    Root<Post> root = q.from(Post.class);
    q.where(root.get("id").in(checkedList));

    int result = em.createQuery(q).executeUpdate();
    log.info("delete @" + result);
    load();
}
 
Example #15
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void delete() {
    final List<Long> checkedList = getCheckedList();
    for (Long id : checkedList) {
        checked.remove(id);
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaDelete<Post> q = cb.createCriteriaDelete(Post.class);
    Root<Post> root = q.from(Post.class);
    q.where(root.get("id").in(checkedList));

    int result = em.createQuery(q).executeUpdate();
    log.info("delete @" + result);
    load();
}
 
Example #16
Source File: JtaEntityManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Query createQuery(final CriteriaDelete deleteQuery) {
    final Timer timer = Op.createQuery.start(this.timer, this);
    try {
        return getEntityManager().createQuery(deleteQuery);
    } finally {
        timer.stop();
    }
}
 
Example #17
Source File: Filter.java    From activejpa with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs the delete criteria query
 * 
 * @param builder
 * @param query
 * @param root
 */
<T extends Model> void constructQuery(CriteriaBuilder builder, CriteriaDelete<?> query, Root<T> root) {
	if (!conditions.isEmpty()) {
		List<Predicate> predicates = new ArrayList<Predicate>();
		for (Condition condition : conditions) {
			predicates.add(condition.constructQuery(builder, root));
		}
		query.where(predicates.toArray(new Predicate[0]));
	}
}
 
Example #18
Source File: Model.java    From activejpa with Apache License 2.0 5 votes vote down vote up
protected static <T extends Model> void deleteAll(final Class<T> clazz, final Filter filter) {
	execute(manager -> {
		CriteriaBuilder builder = manager.getCriteriaBuilder();
		CriteriaDelete<T> deleteQuery = builder.createCriteriaDelete(clazz);
		Root<T> root = deleteQuery.from(clazz);
		filter.constructQuery(builder, deleteQuery, root);
		Query query = createQuery(deleteQuery, filter);
		return query.executeUpdate();
	}, false);
}
 
Example #19
Source File: FilterTest.java    From activejpa with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConstructCriteriaDeleteQuery() {
	Filter filter = new Filter(mock(Condition.class), mock(Condition.class));
	CriteriaBuilder builder = mock(CriteriaBuilder.class);
	Root root = mock(Root.class);
	Predicate p1 = mock(Predicate.class);
	Predicate p2 = mock(Predicate.class);
	when(filter.getConditions().get(0).constructQuery(builder, root)).thenReturn(p1);
	when(filter.getConditions().get(1).constructQuery(builder, root)).thenReturn(p2);
	CriteriaDelete query = mock(CriteriaDelete.class);
	filter.constructQuery(builder, query, root);
	verify(query).where(p1, p2);
}
 
Example #20
Source File: ActionRowDeleteBatch.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private <T extends JpaObject> Integer delete(Business business, Class<T> cls, List<String> ids) throws Exception {
	EntityManager em = business.entityManagerContainer().get(cls);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaDelete<T> cd = cb.createCriteriaDelete(cls);
	Root<T> root = cd.from(cls);
	Predicate p = cb.isMember(root.get(JpaObject.id_FIELDNAME), cb.literal(ids));
	return em.createQuery(cd.where(p)).executeUpdate();

}
 
Example #21
Source File: MechanismEntityService.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 根据主文档删除,fdEntityKey可为空,不触发相关事件
 */
public <E extends IEntity> void deleteByEntity(Class<E> clazz,
		String fdEntityName, String fdEntityId, String fdEntityKey) {
	IteratorQueryTemplate<E> template = new IteratorQueryTemplate<>(
			entityManager, clazz).setFetchSize(1).setAutoFlush(false);
	IteratorQueryTemplate<E>.QueryIterator iterator = template
			.iterator(buildRequest(fdEntityName, fdEntityId, fdEntityKey));
	if (iterator.isEmpty()) {
		return;
	}
	CriteriaDelete<E> query = entityManager.getCriteriaBuilder()
			.createCriteriaDelete(clazz);
	query.where(query.from(clazz).get("fdId").in(iterator.getIds()));
	entityManager.createQuery(query).executeUpdate();
}
 
Example #22
Source File: JpaNoRollbackTest.java    From micronaut-test with Apache License 2.0 5 votes vote down vote up
@AfterAll
void cleanup() {
    final TransactionStatus tx = transactionManager.getTransaction(new DefaultTransactionDefinition());
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaDelete<Book> delete = criteriaBuilder.createCriteriaDelete(Book.class);
    delete.from(Book.class);
    entityManager.createQuery(delete).executeUpdate();
    transactionManager.commit(tx);
}
 
Example #23
Source File: SCCCachingFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Clear all repositories from the database.
 */
public static void clearRepositories() {
    //getSession().getNamedQuery("SCCRepository.deleteAll").executeUpdate();
    CriteriaBuilder builder = getSession().getCriteriaBuilder();
    CriteriaDelete<SCCRepository> delete = builder.createCriteriaDelete(SCCRepository.class);
    CriteriaDelete<SCCRepositoryAuth> deleteAuth = builder.createCriteriaDelete(SCCRepositoryAuth.class);
    delete.from(SCCRepository.class);
    deleteAuth.from(SCCRepositoryAuth.class);
    getSession().createQuery(deleteAuth).executeUpdate();
    getSession().createQuery(delete).executeUpdate();
}
 
Example #24
Source File: SCCCachingFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Clear all subscriptions from the database.
 */
public static void clearSubscriptions() {
    //getSession().getNamedQuery("SCCSubscription.deleteAll").executeUpdate();
    CriteriaBuilder builder = getSession().getCriteriaBuilder();
    CriteriaDelete<SCCSubscription> delete = builder.createCriteriaDelete(SCCSubscription.class);
    Root d = delete.from(SCCSubscription.class);
    getSession().createQuery(delete).executeUpdate();

}
 
Example #25
Source File: SCCCachingFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Clear all subscriptions from the database assigned to the
 * credential.
 * @param c the credentials
 */
public static void clearSubscriptions(Credentials c) {
    if (c == null) {
        clearSubscriptions();
        return;
    }
    CriteriaBuilder builder = getSession().getCriteriaBuilder();
    CriteriaDelete<SCCSubscription> delete = builder.createCriteriaDelete(SCCSubscription.class);
    Root<SCCSubscription> e = delete.from(SCCSubscription.class);
    delete.where(builder.equal(e.get("credentials"), c));
    getSession().createQuery(delete).executeUpdate();
}
 
Example #26
Source File: UserNotificationFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delete all notification messages that were created before a given date.
 *
 * @param before all notifications created before this date will be deleted
 * @return int number of deleted notification messages
 */
public static int deleteNotificationMessagesBefore(Date before) {
    CriteriaBuilder builder = getSession().getCriteriaBuilder();
    CriteriaDelete<NotificationMessage> delete = builder.createCriteriaDelete(NotificationMessage.class);
    Root<NotificationMessage> root = delete.from(NotificationMessage.class);
    delete.where(builder.lessThan(root.<Date>get("created"), before));
    return getSession().createQuery(delete).executeUpdate();
}
 
Example #27
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Query createQuery(CriteriaDelete deleteQuery) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        return emr.em.createQuery(deleteQuery);
    }
}
 
Example #28
Source File: ActionRowDeleteBatch.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private <T extends JpaObject> Integer delete(Business business, Class<T> cls, List<String> ids) throws Exception {
	EntityManager em = business.entityManagerContainer().get(cls);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaDelete<T> cd = cb.createCriteriaDelete(cls);
	Root<T> root = cd.from(cls);
	Predicate p = cb.isMember(root.get(JpaObject.id_FIELDNAME), cb.literal(ids));
	return em.createQuery(cd.where(p)).executeUpdate();

}
 
Example #29
Source File: TestEntityManager.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Query createQuery( CriteriaDelete cd )
{
    // TODO Auto-generated method stub
    return null;
}
 
Example #30
Source File: BaseObject.java    From activejpa with Apache License 2.0 4 votes vote down vote up
protected static <T> Query createQuery(CriteriaDelete<T> cQuery, Filter filter) {
	Query query = getEntityManager().createQuery(cQuery);
	updateQueryParams(query, filter);
	return query;
}