javax.persistence.criteria.CriteriaUpdate#where ( )源码实例Demo

下面列出了javax.persistence.criteria.CriteriaUpdate#where ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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();
}
 
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();
}
 
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();
}
 
@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());
}
 
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();
}
 
源代码6 项目: hibernate-reactive   文件: QueryTest.java
@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() )
	);
}
 
源代码7 项目: hibernate-reactive   文件: QueryTest.java
@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() )
	);
}
 
源代码8 项目: statefulj   文件: JPAPerister.java
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;
}