Java Code Examples for javax.persistence.criteria.CriteriaUpdate#set()

The following examples show how to use javax.persistence.criteria.CriteriaUpdate#set() . 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: 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 3
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 4
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 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: 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 7
Source File: QueryTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testCriteriaEntityQuery(TestContext context) {
	Author author1 = new Author("Iain M. Banks");
	Author author2 = new Author("Neal Stephenson");
	Book book1 = new Book("1-85723-235-6", "Feersum Endjinn", author1);
	Book book2 = new Book("0-380-97346-4", "Cryptonomicon", author2);
	Book book3 = new Book("0-553-08853-X", "Snow Crash", author2);
	author1.books.add(book1);
	author2.books.add(book2);
	author2.books.add(book3);

	CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder();
	CriteriaQuery<Book> query = builder.createQuery(Book.class);
	Root<Book> b = query.from(Book.class);
	b.fetch("author");
	query.orderBy( builder.asc( b.get("isbn") ) );

	CriteriaUpdate<Book> update = builder.createCriteriaUpdate(Book.class);
	b = update.from(Book.class);
	update.set( b.get("title"), "XXX" );

	CriteriaDelete<Book> delete = builder.createCriteriaDelete(Book.class);
	b = delete.from(Book.class);

	test(context,
			openSession()
					.thenCompose( session -> session.persist(author1, author2) )
					.thenCompose( session -> session.flush() )
					.whenComplete( (session,err) -> session.close() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(query).getResultList() )
					.thenAccept( books -> {
						context.assertEquals( 3, books.size() );
						books.forEach( book -> {
							context.assertNotNull( book.id );
							context.assertNotNull( book.title );
							context.assertNotNull( book.isbn );
						} );
					} )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(update).executeUpdate() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(delete).executeUpdate() )
	);
}
 
Example 8
Source File: QueryTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testCriteriaEntityQueryWithParam(TestContext context) {
	Author author1 = new Author("Iain M. Banks");
	Author author2 = new Author("Neal Stephenson");
	Book book1 = new Book("1-85723-235-6", "Feersum Endjinn", author1);
	Book book2 = new Book("0-380-97346-4", "Cryptonomicon", author2);
	Book book3 = new Book("0-553-08853-X", "Snow Crash", author2);
	author1.books.add(book1);
	author2.books.add(book2);
	author2.books.add(book3);

	CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder();
	CriteriaQuery<Book> query = builder.createQuery(Book.class);
	Root<Book> b = query.from(Book.class);
	b.fetch("author");
	ParameterExpression<String> t = builder.parameter(String.class);
	query.where( builder.equal( b.get("title"), t ) );
	query.orderBy( builder.asc( b.get("isbn") ) );

	CriteriaUpdate<Book> update = builder.createCriteriaUpdate(Book.class);
	b = update.from(Book.class);
	update.where( builder.equal( b.get("title"), t ) );
	update.set( b.get("title"), "XXX" );

	CriteriaDelete<Book> delete = builder.createCriteriaDelete(Book.class);
	b = delete.from(Book.class);
	delete.where( builder.equal( b.get("title"), t ) );

	test(context,
			openSession()
					.thenCompose( session -> session.persist(author1, author2) )
					.thenCompose( session -> session.flush() )
					.whenComplete( (session,err) -> session.close() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(query)
							.setParameter( t, "Snow Crash")
							.getResultList() )
					.thenAccept( books -> {
						context.assertEquals( 1, books.size() );
						books.forEach( book -> {
							context.assertNotNull( book.id );
							context.assertNotNull( book.title );
							context.assertNotNull( book.isbn );
							context.assertEquals( "Snow Crash", book.title );
						} );
					} )

					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(update)
							.setParameter( t, "Snow Crash")
							.executeUpdate() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(delete)
							.setParameter( t, "Snow Crash")
							.executeUpdate() )
	);
}
 
Example 9
Source File: QueryTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testCriteriaEntityQueryWithNamedParam(TestContext context) {
	Author author1 = new Author("Iain M. Banks");
	Author author2 = new Author("Neal Stephenson");
	Book book1 = new Book("1-85723-235-6", "Feersum Endjinn", author1);
	Book book2 = new Book("0-380-97346-4", "Cryptonomicon", author2);
	Book book3 = new Book("0-553-08853-X", "Snow Crash", author2);
	author1.books.add(book1);
	author2.books.add(book2);
	author2.books.add(book3);

	CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder();
	CriteriaQuery<Book> query = builder.createQuery(Book.class);
	Root<Book> b = query.from(Book.class);
	b.fetch("author");
	ParameterExpression<String> t = builder.parameter(String.class, "title");
	query.where( builder.equal( b.get("title"), t ) );
	query.orderBy( builder.asc( b.get("isbn") ) );

	CriteriaUpdate<Book> update = builder.createCriteriaUpdate(Book.class);
	b = update.from(Book.class);
	update.where( builder.equal( b.get("title"), t ) );
	update.set( b.get("title"), "XXX" );

	CriteriaDelete<Book> delete = builder.createCriteriaDelete(Book.class);
	b = delete.from(Book.class);
	delete.where( builder.equal( b.get("title"), t ) );

	test(context,
			openSession()
					.thenCompose( session -> session.persist(author1, author2) )
					.thenCompose( session -> session.flush() )
					.whenComplete( (session,err) -> session.close() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(query)
							.setParameter("title", "Snow Crash")
							.getResultList() )
					.thenAccept( books -> {
						context.assertEquals( 1, books.size() );
						books.forEach( book -> {
							context.assertNotNull( book.id );
							context.assertNotNull( book.title );
							context.assertNotNull( book.isbn );
							context.assertEquals( "Snow Crash", book.title );
						} );
					} )

					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(update)
							.setParameter("title", "Snow Crash")
							.executeUpdate() )
					.thenCompose( v -> openSession() )
					.thenCompose( session -> session.createQuery(delete)
							.setParameter("title", "Snow Crash")
							.executeUpdate() )
	);
}
 
Example 10
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;
}