javax.persistence.criteria.CriteriaUpdate Java Examples

The following examples show how to use javax.persistence.criteria.CriteriaUpdate. 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: SoftDeletesRepositoryImpl.java    From spring-boot-jpa-data-rest-soft-delete with MIT License 8 votes vote down vote up
private void softDelete(T entity, LocalDateTime localDateTime) {
	Assert.notNull(entity, "The entity must not be null!");

	CriteriaBuilder cb = em.getCriteriaBuilder();

	CriteriaUpdate<T> update = cb.createCriteriaUpdate((Class<T>) domainClass);

	Root<T> root = update.from((Class<T>) domainClass);

	update.set(DELETED_FIELD, localDateTime);

	final List<Predicate> predicates = new ArrayList<Predicate>();

	if (entityInformation.hasCompositeId()) {
		for (String s : entityInformation.getIdAttributeNames())
			predicates.add(cb.equal(root.<ID>get(s),
					entityInformation.getCompositeIdAttributeValue(entityInformation.getId(entity), s)));
		update.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
	} else
		update.where(cb.equal(root.<ID>get(entityInformation.getIdAttribute().getName()),
				entityInformation.getId(entity)));

	em.createQuery(update).executeUpdate();
}
 
Example #2
Source File: JpaNestedNodeMovingQueryDelegate.java    From nestedj with MIT License 7 votes vote down vote up
private void updateFields(Mode mode, Long delta, Long start, Long stop, String field) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);

    if (Mode.DOWN.equals(mode)) {
        update.set(root.<Long>get(field), cb.diff(root.get(field), delta));
    } else if (Mode.UP.equals(mode)) {
        update.set(root.<Long>get(field), cb.sum(root.get(field), delta));
    }
    update.where(getPredicates(cb, root,
            cb.greaterThan(root.get(field), start),
            cb.lessThan(root.get(field), stop)
    ));
    entityManager.createQuery(update).executeUpdate();
}
 
Example #3
Source File: HibernateImmutableWarningTest.java    From high-performance-java-persistence with Apache License 2.0 7 votes vote down vote up
@Test
public void testCriteriaAPI() {

    doInJPA(entityManager -> {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaUpdate<Event> update = builder.createCriteriaUpdate(Event.class);

        Root<Event> root = update.from(Event.class);

        update
        .set(root.get("eventValue"), "100")
        .where(
            builder.equal(root.get("id"), 1L)
        );

        entityManager.createQuery(update).executeUpdate();
    });

    doInJPA(entityManager -> {
        Event event = entityManager.find(Event.class, 1L);

        assertEquals("100", event.getEventValue());
    });
}
 
Example #4
Source File: TestCriteriaUpdate.java    From HibernateTips with MIT License 7 votes vote down vote up
@Test
public void updateBookPrices() {
	log.info("... updateBookPrices ...");

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

	logBookPrices(em);
	
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaUpdate<Book> update = cb.createCriteriaUpdate(Book.class);
	Root<Book> root = update.from(Book.class);
	update.set(Book_.price, cb.prod(root.get(Book_.price), 1.1));
	
	Query query = em.createQuery(update);
	query.executeUpdate();

	logBookPrices(em);
	
	em.getTransaction().commit();
	em.close();
}
 
Example #5
Source File: HibernateCriteriaIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNewItemPrice_whenCriteriaUpdate_thenReturnAffectedResult() {

    int oldPrice = 10, newPrice = 20;

    Session session = HibernateUtil.getHibernateSession();

    Item item = new Item(12, "Test Item 12", "This is a description");
    item.setItemPrice(oldPrice);
    session.save(item);

    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaUpdate<Item> criteriaUpdate = cb.createCriteriaUpdate(Item.class);
    Root<Item> root = criteriaUpdate.from(Item.class);
    criteriaUpdate.set("itemPrice", newPrice);
    criteriaUpdate.where(cb.equal(root.get("itemPrice"), oldPrice));

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

    Item updatedItem = session.createQuery("FROM Item WHERE itemPrice = " + newPrice, Item.class).getSingleResult();
    session.refresh(updatedItem);
    assertEquals(newPrice, updatedItem.getItemPrice().intValue());
}
 
Example #6
Source File: JpaNestedNodeMovingQueryDelegate.java    From nestedj with MIT License 6 votes vote down vote up
private void performMove(Mode mode, Long nodeDelta, Long levelModificator) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);

    update.set(root.<Long>get(LEVEL), cb.sum(root.get(LEVEL), levelModificator));
    if (Mode.DOWN.equals(mode)) {
        update.set(root.<Long>get(RIGHT), cb.diff(unMarkRightField(root), nodeDelta));
        update.set(root.<Long>get(LEFT), cb.diff(root.get(LEFT), nodeDelta));
    } else if (Mode.UP.equals(mode)) {
        update.set(root.<Long>get(RIGHT), cb.sum(unMarkRightField(root), nodeDelta));
        update.set(root.<Long>get(LEFT), cb.sum(root.get(LEFT), nodeDelta));
    }
    update.where(
            getPredicates(cb, root, cb.lessThan(root.get(RIGHT), 0))
    );
    entityManager.createQuery(update).executeUpdate();
}
 
Example #7
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void update() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class);
    Root<Post> root = q.from(Post.class);
    q.set(root.get("approved"), true)
            .where(root.get("id").in(getCheckedList()));

    int result = em.createQuery(q).executeUpdate();
    log.info("update @" + result);
    load();
}
 
Example #8
Source File: JpaNestedNodeMovingQueryDelegate.java    From nestedj with MIT License 5 votes vote down vote up
@Override
public Integer markNodeIds(NestedNodeInfo<ID> node) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);
    update
            .set(root.<Long>get(RIGHT), markRightField(root))
            .where(
                    getPredicates(cb, root,
                            cb.greaterThanOrEqualTo(root.get(LEFT), node.getLeft()),
                            cb.lessThanOrEqualTo(root.get(RIGHT), node.getRight())
                    ));
    return entityManager.createQuery(update).executeUpdate();
}
 
Example #9
Source File: HibernateImmutableExceptionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testCriteriaAPI() {

    try {
        doInJPA(entityManager -> {
            CriteriaBuilder builder = entityManager.getCriteriaBuilder();
            CriteriaUpdate<Event> update = builder.createCriteriaUpdate(Event.class);

            Root<Event> root = update.from(Event.class);

            update
            .set(root.get("eventValue"), "100")
            .where(
                builder.equal(root.get("id"), 1L)
            );

            entityManager.createQuery(update).executeUpdate();
        });

        fail("Should have thrown exception");
    } catch (Exception e) {
        HibernateException cause = (HibernateException) e.getCause();
        assertEquals(
            "The query: [" +
            "update Event as generatedAlias0 " +
            "set generatedAlias0.eventValue = :param0 " +
            "where generatedAlias0.id=1L" +
            "] attempts to update an immutable entity: [Event]",
            cause.getMessage()
        );
    }
}
 
Example #10
Source File: JpaNestedNodeMovingQueryDelegate.java    From nestedj with MIT License 5 votes vote down vote up
private void doUpdateParentField(ID newParentId, NestedNodeInfo<ID> node) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);

    update.set(root.get(PARENT_ID), newParentId)
            .where(getPredicates(cb, root, cb.equal(root.get(ID), node.getId())));

    entityManager.createQuery(update).executeUpdate();
}
 
Example #11
Source File: JpaNestedNodeInsertingQueryDelegate.java    From nestedj with MIT License 5 votes vote down vote up
private void updateFields(Long from, String fieldName, boolean gte) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);
    update.set(root.<Long>get(fieldName), cb.sum(root.get(fieldName), INCREMENT_BY));
    if(gte) {
        update.where(getPredicates(cb, root, cb.greaterThanOrEqualTo(root.get(fieldName), from)));
    } else {
        update.where(getPredicates(cb, root, cb.greaterThan(root.get(fieldName), from)));
    }
    entityManager.createQuery(update).executeUpdate();
}
 
Example #12
Source File: JpaNestedNodeRebuildingQueryDelegate.java    From nestedj with MIT License 5 votes vote down vote up
@Override
public void destroyTree() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);
    update
            .set(root.<Long>get(LEFT), 0L)
            .set(root.<Long>get(RIGHT), 0L)
            .set(root.<Long>get(LEVEL), 0L)
            .where(getPredicates(cb, root));

    entityManager.createQuery(update).executeUpdate();
}
 
Example #13
Source File: JpaNestedNodeRebuildingQueryDelegate.java    From nestedj with MIT License 5 votes vote down vote up
@Override
public void resetFirst(N first) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass);
    Root<N> root = update.from(nodeClass);
    update
            .set(root.<Long>get(LEVEL), 0L)
            .set(root.<Long>get(LEFT), 1L)
            .set(root.<Long>get(RIGHT), 2L)
            .where(getPredicates(cb, root, cb.equal(update.getRoot().get(ID), first.getId())));
    entityManager.createQuery(update).executeUpdate();
}
 
Example #14
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public QueryImplementor createQuery(CriteriaUpdate criteriaUpdate) {
	checkOpen();
	try {
		return criteriaCompiler().compile( (CompilableCriteria) criteriaUpdate );
	}
	catch ( RuntimeException e ) {
		throw exceptionConverter.convert( e );
	}
}
 
Example #15
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void update() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class);
    Root<Post> root = q.from(Post.class);
    q.set(root.get("approved"), true)
            .where(root.get("id").in(getCheckedList()));

    int result = em.createQuery(q).executeUpdate();
    log.info("update @" + result);
    load();
}
 
Example #16
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void update() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class);
    Root<Post> root = q.from(Post.class);
    q.set(root.get("approved"), true)
            .where(root.get("id").in(getCheckedList()));

    int result = em.createQuery(q).executeUpdate();
    log.info("update @" + result);
    load();
}
 
Example #17
Source File: CriteriaUpdateImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public CriteriaUpdate<T> set(String attributeName, Object value) {
	final Path attributePath = getRoot().get( attributeName );
	final Expression valueExpression = value == null
			? criteriaBuilder().nullLiteral( attributePath.getJavaType() )
			: criteriaBuilder().literal( value );
	addAssignment( attributePath, valueExpression );
	return this;
}
 
Example #18
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void update() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class);
    Root<Post> root = q.from(Post.class);
    q.set(root.get("approved"), true)
            .where(root.get("id").in(getCheckedList()));

    int result = em.createQuery(q).executeUpdate();
    log.info("update @" + result);
    load();
}
 
Example #19
Source File: CriteriaUpdateImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <Y, X extends Y> CriteriaUpdate<T> set(Path<Y> attributePath, X value) {
	final Expression valueExpression = value == null
			? criteriaBuilder().nullLiteral( attributePath.getJavaType() )
			: criteriaBuilder().literal( value );
	addAssignment( attributePath, valueExpression );
	return this;
}
 
Example #20
Source File: CriteriaUpdateImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <Y> CriteriaUpdate<T> set(
		SingularAttribute<? super T, Y> singularAttribute,
		Expression<? extends Y> value) {
	addAssignment( getRoot().get( singularAttribute ), value );
	return this;
}
 
Example #21
Source File: CriteriaUpdateImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <Y, X extends Y> CriteriaUpdate<T> set(SingularAttribute<? super T, Y> singularAttribute, X value) {
	final Path<Y> attributePath = getRoot().get( singularAttribute );
	final Expression valueExpression = value == null
			? criteriaBuilder().nullLiteral( attributePath.getJavaType() )
			: criteriaBuilder().literal( value );
	addAssignment( attributePath, valueExpression );
	return this;
}
 
Example #22
Source File: PostsBean.java    From ee7-sandbox with Apache License 2.0 5 votes vote down vote up
public void update() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class);
    Root<Post> root = q.from(Post.class);
    q.set(root.get("approved"), true)
            .where(root.get("id").in(getCheckedList()));

    int result = em.createQuery(q).executeUpdate();
    log.info("update @" + result);
    load();
}
 
Example #23
Source File: JtaEntityManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Query createQuery(final CriteriaUpdate updateQuery) {
    final Timer timer = Op.createQuery.start(this.timer, this);
    try {
        return getEntityManager().createQuery(updateQuery);
    } finally {
        timer.stop();
    }
}
 
Example #24
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        return emr.em.createQuery(updateQuery);
    }
}
 
Example #25
Source File: SyncEntityManagerWrapper.java    From kumuluzee with MIT License 4 votes vote down vote up
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
    return em.createQuery(updateQuery);
}
 
Example #26
Source File: JPAPerister.java    From statefulj with Apache License 2.0 4 votes vote down vote up
protected Query buildUpdate(
		Object id,
		T stateful,
		State<T> current,
		State<T> next,
		Field idField,
		Field stateField) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException {

	CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();

	// update <class>
	//
	CriteriaUpdate<T> cu = cb.createCriteriaUpdate(this.getClazz());
	Root<T> t = cu.from(this.getClazz());

	Path<?> idPath = t.get(this.getIdField().getName());
	Path<String> statePath = t.get(this.getStateField().getName());

	// set state=<next_state>
	//
	cu.set(statePath, next.getName());

	// where id=<id> and state=<current_state>
	//
	Predicate statePredicate = (current.equals(getStartState())) ?
			cb.or(
				cb.equal(
					statePath,
					current.getName()
				),
				cb.equal(
					statePath,
					cb.nullLiteral(String.class)
				)
			) :
			cb.equal(
				statePath,
				current.getName()
			);

	cu.where(
		cb.and(
			cb.equal(
				idPath,
				this.getId(stateful)
			),
			statePredicate
		)
	);

	Query query = entityManager.createQuery(cu);
	if (logger.isDebugEnabled()) {
		logger.debug(query.unwrap(org.hibernate.Query.class).getQueryString());
	}
	return query;
}
 
Example #27
Source File: EntityManagerWrapper.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
	return em.createQuery(updateQuery);
}
 
Example #28
Source File: SharedContextAwareEntityManagerProxy.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
	return em().createQuery(updateQuery);
}
 
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( CriteriaUpdate cu )
{
    // TODO Auto-generated method stub
    return null;
}
 
Example #30
Source File: QueryLogEntityManager.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public Query createQuery(final CriteriaUpdate updateQuery) {
    return delegate.createQuery(updateQuery);
}