javax.persistence.criteria.ParameterExpression Java Examples

The following examples show how to use javax.persistence.criteria.ParameterExpression. 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: ReactiveQueryImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 7 votes vote down vote up
private <T> ExplicitParameterInfo<?> resolveParameterInfo(Parameter<T> param) {
	if (param instanceof ExplicitParameterInfo) {
		return (ExplicitParameterInfo<?>) param;
	}
	else if (param instanceof ParameterExpression) {
		return explicitParameterInfoMap.get( param );
	}
	else {
		for ( ExplicitParameterInfo<?> parameterInfo: explicitParameterInfoMap.values() ) {
			if ( param.getName() != null && param.getName().equals( parameterInfo.getName() ) ) {
				return parameterInfo;
			}
			else if ( param.getPosition() != null && param.getPosition().equals( parameterInfo.getPosition() ) ) {
				return parameterInfo;
			}
		}
	}
	throw new IllegalArgumentException( "Unable to locate parameter [" + param + "] in query" );
}
 
Example #2
Source File: RelationshipTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<RelationshipTemplateInstance> findByTemplateId(final String templateId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        // Parameters
        final ParameterExpression<String> templateIdParameter = cb.parameter(String.class);
        // Build the Criteria Query
        final CriteriaQuery<RelationshipTemplateInstance> cq = cb.createQuery(RelationshipTemplateInstance.class);
        final Root<RelationshipTemplateInstance> sti = cq.from(RelationshipTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("templateId"), templateIdParameter));
        // Create a TypedQuery
        final TypedQuery<RelationshipTemplateInstance> q = em.createQuery(cq);
        q.setParameter(templateIdParameter, templateId);
        // Execute
        return q.getResultList();
    }
}
 
Example #3
Source File: TestCriteriaQuery.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void getBooks() {
	log.info("... getBooks ...");

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

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> cq = cb.createQuery(Book.class);
	Root<Book> root = cq.from(Book.class);
	SetJoin<Book, Author> authors = root.join(Book_.authors);
	
	ParameterExpression<String> paramFirstName = cb.parameter(String.class);
	ParameterExpression<String> paramLastName = cb.parameter(String.class);
	cq.where(
		cb.and(
			cb.equal(authors.get(Author_.firstName), paramFirstName), 
			cb.equal(authors.get(Author_.lastName), paramLastName)));
	
	TypedQuery<Book> query = em.createQuery(cq);
	query.setParameter(paramFirstName, "Thorben");
	query.setParameter(paramLastName, "Janssen");
	List<Book> books = query.getResultList();
	Assert.assertEquals(1, books.size());
	
	for (Book b : books) {
		log.info(b);
	}
	
	em.getTransaction().commit();
	em.close();
}
 
Example #4
Source File: TestLogging.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void selectAuthorsCriteria() {
	log.info("... selectAuthorsCriteria ...");

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

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Author> cq = cb.createQuery(Author.class);
	Root<Author> root = cq.from(Author.class);
	cq.select(root);
	ParameterExpression<Long> idParam = cb.parameter(Long.class, "id");
	cq.where(cb.equal(root.get("id"), idParam));
	TypedQuery<Author> q = em.createQuery(cq);
	q.setParameter("id", 1L);
	q.setHint("org.hibernate.comment", "This is my comment");
	q.getSingleResult();

	em.getTransaction().commit();
	em.close();
}
 
Example #5
Source File: FindByMultipleIdsTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testCriteriaAPI() {
    doInJPA(entityManager -> {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Book> query = builder.createQuery(Book.class);
        Root<Book> root = query.from(Book.class);

        ParameterExpression<List> isbn = builder.parameter(List.class);
        query.where(root.get("isbn").in(isbn));

        List<Book> books = entityManager
            .createQuery(query)
            .setParameter(isbn, Arrays.asList(
                "978-9730228236",
                "978-1934356555",
                "978-3950307825"
            ))
            .getResultList();

        assertEquals(3, books.size());
    });
}
 
Example #6
Source File: CriteriaQueryTypeQueryAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private <T> ExplicitParameterInfo<?> resolveParameterInfo(Parameter<T> param) {
	if ( ExplicitParameterInfo.class.isInstance( param ) ) {
		return (ExplicitParameterInfo<?>) param;
	}
	else if ( ParameterExpression.class.isInstance( param ) ) {
		return explicitParameterInfoMap.get( param );
	}
	else {
		for ( ExplicitParameterInfo<?> parameterInfo : explicitParameterInfoMap.values() ) {
			if ( param.getName() != null && param.getName().equals( parameterInfo.getName() ) ) {
				return parameterInfo;
			}
			else if ( param.getPosition() != null && param.getPosition().equals( parameterInfo.getPosition() ) ) {
				return parameterInfo;
			}
		}
	}
	throw new IllegalArgumentException( "Unable to locate parameter [" + param + "] in query" );
}
 
Example #7
Source File: PlanInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public PlanInstance findByCorrelationId(final String correlationId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        // Parameters
        final ParameterExpression<String> correlationIdParameter = cb.parameter(String.class);
        // Build the Criteria Query
        final CriteriaQuery<PlanInstance> cq = cb.createQuery(PlanInstance.class);
        final Root<PlanInstance> sti = cq.from(PlanInstance.class);
        cq.select(sti).where(cb.equal(sti.get("correlationId"), correlationIdParameter));
        // Create a TypedQuery
        final TypedQuery<PlanInstance> q = em.createQuery(cq);
        q.setParameter(correlationIdParameter, correlationId);
        // Execute
        PlanInstance result = q.getSingleResult();
        initializeInstance(result);
        return result;
    }
}
 
Example #8
Source File: ServiceTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<ServiceTemplateInstance> findByTemplateId(final String templateId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        // Parameters
        final ParameterExpression<String> templateIdParameter = cb.parameter(String.class);
        // Build the Criteria Query
        final CriteriaQuery<ServiceTemplateInstance> cq = cb.createQuery(ServiceTemplateInstance.class);
        final Root<ServiceTemplateInstance> sti = cq.from(ServiceTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("templateId"), templateIdParameter));
        // Create a TypedQuery
        final TypedQuery<ServiceTemplateInstance> q = em.createQuery(cq);
        q.setParameter(templateIdParameter, templateId);
        // Execute
        List<ServiceTemplateInstance> results = q.getResultList();
        results.forEach(this::initializeInstance);
        return results;
    }
}
 
Example #9
Source File: ServiceTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<ServiceTemplateInstance> findByCsarId(final CsarId csarId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        // Parameters
        final ParameterExpression<CsarId> csarIdParameter = cb.parameter(CsarId.class);
        // Build the Criteria Query
        final CriteriaQuery<ServiceTemplateInstance> cq = cb.createQuery(ServiceTemplateInstance.class);
        final Root<ServiceTemplateInstance> sti = cq.from(ServiceTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("csarId"), csarIdParameter));
        // Create a TypedQuery
        final TypedQuery<ServiceTemplateInstance> q = em.createQuery(cq);
        q.setParameter(csarIdParameter, csarId);
        // Execute
        List<ServiceTemplateInstance> results = q.getResultList();
        results.forEach(this::initializeInstance);
        return results;
    }
}
 
Example #10
Source File: NodeTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public List<NodeTemplateInstance> find(final ServiceTemplateInstance sti, String nodeTemplateId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();

        final ParameterExpression<ServiceTemplateInstance> owner = cb.parameter(ServiceTemplateInstance.class, "sti");
        final ParameterExpression<String> templateId = cb.parameter(String.class, "ntId");

        final CriteriaQuery<NodeTemplateInstance> query = cb.createQuery(NodeTemplateInstance.class);
        final Root<NodeTemplateInstance> nti = query.from(NodeTemplateInstance.class);

        query.select(nti).where(
            cb.equal(nti.get("serviceTemplateInstance"), owner)
            , cb.equal(nti.get("templateId"), templateId));

        final TypedQuery<NodeTemplateInstance> q = em.createQuery(query);
        q.setParameter(owner, sti);
        q.setParameter(templateId, nodeTemplateId);

        final List<NodeTemplateInstance> result = q.getResultList();
        result.forEach(this::initializeInstance);
        return result;
    }
}
 
Example #11
Source File: NodeTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<NodeTemplateInstance> findByTemplateId(final String templateId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();

        final ParameterExpression<String> templateIdParameter = cb.parameter(String.class);

        final CriteriaQuery<NodeTemplateInstance> cq = cb.createQuery(NodeTemplateInstance.class);
        final Root<NodeTemplateInstance> sti = cq.from(NodeTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("templateId"), templateIdParameter));

        final TypedQuery<NodeTemplateInstance> q = em.createQuery(cq);
        q.setParameter(templateIdParameter, templateId);

        return q.getResultList();
    }
}
 
Example #12
Source File: NodeTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<NodeTemplateInstance> findByTemplateType(final QName templateType) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();

        final ParameterExpression<QName> templateTypeParameter = cb.parameter(QName.class);

        final CriteriaQuery<NodeTemplateInstance> cq = cb.createQuery(NodeTemplateInstance.class);
        final Root<NodeTemplateInstance> sti = cq.from(NodeTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("templateType"), templateTypeParameter));

        final TypedQuery<NodeTemplateInstance> q = em.createQuery(cq);
        q.setParameter(templateTypeParameter, templateType);

        return q.getResultList();
    }
}
 
Example #13
Source File: BindArrayTypeQueryParameterTest.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@Test
public void testCriteriaAPI() {
    doInJPA(entityManager -> {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Event> cq = cb.createQuery(Event.class);
        Root<Event> root = cq.from(Event.class);
        cq.select(root);

        ParameterExpression containValues = cb.parameter(int[].class, "arrayValues");
        cq.where(
            cb.equal(
                cb.function(
                    "fn_array_contains",
                    Boolean.class,
                    root.get("values"), containValues
                ),
                Boolean.TRUE
            )
        );

        Event event = (Event) entityManager
        .createQuery(cq)
        .unwrap(Query.class)
        .setParameter("arrayValues", new int[]{2, 3}, IntArrayType.INSTANCE)
        .getSingleResult();

        assertArrayEquals(new int[]{1, 2, 3}, event.getValues());
    });
}
 
Example #14
Source File: FailOnPaginationWithCollectionFetchTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchAndPaginateWithCriteriaApi() {
    doInJPA(entityManager -> {
        try {
            CriteriaBuilder builder = entityManager.getCriteriaBuilder();
            CriteriaQuery<Post> criteria = builder.createQuery(Post.class);

            Root<Post> post = criteria.from(Post.class);
            post.fetch("comments");

            ParameterExpression<String> parameterExpression = builder.parameter(String.class);

            criteria.where(
                builder.like(
                    post.get("title"),
                    parameterExpression
                )
            )
            .orderBy(
                builder.asc(
                    post.get("createdOn")
                )
            );

            entityManager
            .createQuery(criteria)
            .setParameter(parameterExpression, "High-Performance Java Persistence %")
            .setMaxResults(5)
            .getResultList();

            fail("Should have thrown Exception");
        } catch (Exception e) {
            assertTrue(e.getMessage().contains("In memory pagination was about to be applied"));
        }
    });
}
 
Example #15
Source File: JpaBenchmark.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void findByTitleCriteria(Blackhole sink) {

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> q = cb.createQuery(Book.class);
	Root<Book> c = q.from(Book.class);

	ParameterExpression<String> parameter = cb.parameter(String.class);

	TypedQuery<Book> query = em.createQuery(q.select(c).where(cb.equal(c.get("title"), parameter)));
	query.setParameter(parameter, "title0");

	sink.consume(query.getSingleResult());
}
 
Example #16
Source File: TestCriteriaConstructor.java    From HibernateTips with MIT License 5 votes vote down vote up
@Test
public void callFunction() {
	log.info("... callFunction ...");

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

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> cq = cb.createQuery(Book.class);
	Root<Book> root = cq.from(Book.class);
	
	ParameterExpression<Double> doubleParam1 = cb.parameter(Double.class);
	ParameterExpression<Double> doubleParam2 = cb.parameter(Double.class);
	cq.where(cb.greaterThan(doubleParam2, cb.function("calculate", Double.class, root.get(Book_.price), doubleParam1)));

	TypedQuery<Book> q = em.createQuery(cq);
	q.setParameter(doubleParam1, 10.0D);
	q.setParameter(doubleParam2, 40.0D);
	List<Book> books = q.getResultList();
	
	for (Book b : books) {
		log.info(b);
	}

	em.getTransaction().commit();
	em.close();
}
 
Example #17
Source File: ConditionTest.java    From activejpa with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() {
	builder = mock(CriteriaBuilder.class);
	path = mock(Path.class);
	when(path.getJavaType()).thenReturn(String.class);
	expression = mock(ParameterExpression.class);
	root = mock(Root.class);
	query = mock(Query.class);
	Parameter param = mock(Parameter.class);
	when(param.getParameterType()).thenReturn(String.class);
	when(query.getParameter(anyString())).thenReturn(param);
	
}
 
Example #18
Source File: QueryStructure.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Set<ParameterExpression<?>> getParameters() {
	final Set<ParameterExpression<?>> parameters = new LinkedHashSet<ParameterExpression<?>>();
	final ParameterRegistry registry = new ParameterRegistry() {
		public void registerParameter(ParameterExpression<?> parameter) {
			parameters.add( parameter );
		}
	};

	ParameterContainer.Helper.possibleParameter(selection, registry);
	ParameterContainer.Helper.possibleParameter(restriction, registry);
	ParameterContainer.Helper.possibleParameter(having, registry);
	if ( subqueries != null ) {
		for ( Subquery subquery : subqueries ) {
			ParameterContainer.Helper.possibleParameter(subquery, registry);
		}
	}

	// both group-by and having expressions can (though unlikely) contain parameters...
	ParameterContainer.Helper.possibleParameter(having, registry);
	if ( groupings != null ) {
		for ( Expression<?> grouping : groupings ) {
			ParameterContainer.Helper.possibleParameter(grouping, registry);
		}
	}

	return parameters;
}
 
Example #19
Source File: CriteriaBuilderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ParameterExpression<T> parameter(Class<T> paramClass, String name) {
	return new ParameterExpressionImpl<T>(
			this,
			paramClass,
			name
	);
}
 
Example #20
Source File: CriteriaBuilderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ParameterExpression<T> parameter(Class<T> paramClass) {
	return new ParameterExpressionImpl<T>(
			this,
			paramClass
	);
}
 
Example #21
Source File: CriteriaQueryTypeQueryAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public CriteriaQueryTypeQueryAdapter(
		SessionImplementor entityManager,
		QueryImplementor<X> jpqlQuery,
		Map<ParameterExpression<?>, ExplicitParameterInfo<?>> explicitParameterInfoMap) {
	this.entityManager = entityManager;
	this.jpqlQuery = jpqlQuery;
	this.explicitParameterInfoMap = explicitParameterInfoMap;
}
 
Example #22
Source File: CriteriaQueryRenderingContext.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ExplicitParameterInfo<?> registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter) {
	ExplicitParameterInfo<?> parameterInfo = explicitParameterInfoMap.get( criteriaQueryParameter );
	if ( parameterInfo == null ) {
		if ( StringHelper.isNotEmpty( criteriaQueryParameter.getName() ) ) {
			parameterInfo = new ExplicitParameterInfo<>(
					criteriaQueryParameter.getName(),
					null,
					criteriaQueryParameter.getJavaType()
			);
		}
		else if ( criteriaQueryParameter.getPosition() != null ) {
			parameterInfo = new ExplicitParameterInfo<>(
					null,
					criteriaQueryParameter.getPosition(),
					criteriaQueryParameter.getJavaType()
			);
		}
		else {
			parameterInfo = new ExplicitParameterInfo<>(
					generateParameterName(),
					null,
					criteriaQueryParameter.getJavaType()
			);
		}

		explicitParameterInfoMap.put( criteriaQueryParameter, parameterInfo );
	}

	return parameterInfo;
}
 
Example #23
Source File: VirtualAssetService.java    From mojito with Apache License 2.0 4 votes vote down vote up
@Transactional
List<AssetTextUnitDTO> findByAssetExtractionIdAndDoNotTranslateFilter(Long assetExtractionId, Boolean doNotTranslateFilter) {

    Map<ParameterExpression, Object> parameters = new LinkedHashMap<>();

    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<AssetTextUnitDTO> query = criteriaBuilder.createQuery(AssetTextUnitDTO.class);

    Root<AssetTextUnit> assetTextUnitRoot = query.from(AssetTextUnit.class);

    Predicate conjunction = criteriaBuilder.conjunction();

    ParameterExpression<Long> assetExtractionIdParameter = criteriaBuilder.parameter(Long.class);
    parameters.put(assetExtractionIdParameter, assetExtractionId);
    conjunction.getExpressions().add(criteriaBuilder.equal(assetTextUnitRoot.get(AssetTextUnit_.assetExtraction).get(AssetExtraction_.id), assetExtractionIdParameter));

    if (doNotTranslateFilter != null) {
        ParameterExpression<String> doNotTranslateFilterParameter = criteriaBuilder.parameter(String.class);
        parameters.put(doNotTranslateFilterParameter, doNotTranslateFilter);
        conjunction.getExpressions().add(criteriaBuilder.equal(assetTextUnitRoot.get(AssetTextUnit_.doNotTranslate), doNotTranslateFilterParameter));
    }

    query.select(criteriaBuilder.construct(AssetTextUnitDTO.class,
            assetTextUnitRoot.get(AssetTextUnit_.name),
            assetTextUnitRoot.get(AssetTextUnit_.content),
            assetTextUnitRoot.get(AssetTextUnit_.comment),
            assetTextUnitRoot.get(AssetTextUnit_.pluralForm).get(PluralForm_.id),
            assetTextUnitRoot.get(AssetTextUnit_.pluralFormOther),
            assetTextUnitRoot.get(AssetTextUnit_.md5),
            assetTextUnitRoot.get(AssetTextUnit_.doNotTranslate)
    ));

    query.where(conjunction);
    query.orderBy(criteriaBuilder.asc(assetTextUnitRoot.get(AssetTextUnit_.name)));

    TypedQuery<AssetTextUnitDTO> typedQuery = em.createQuery(query);

    parameters.forEach((parameterExpression, o) -> {
        typedQuery.setParameter(parameterExpression, o);
    });

    List<AssetTextUnitDTO> resultList = typedQuery.getResultList();
    return resultList;
}
 
Example #24
Source File: CriteriaSubqueryImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void registerParameters(ParameterRegistry registry) {
	for ( ParameterExpression param : queryStructure.getParameters() ) {
		registry.registerParameter( param );
	}
}
 
Example #25
Source File: CriteriaQueryImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Set<ParameterExpression<?>> getParameters() {
	return queryStructure.getParameters();
}
 
Example #26
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 #27
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 #28
Source File: CriteriaQueryRenderingContext.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public Map<ParameterExpression<?>, ExplicitParameterInfo<?>> explicitParameterInfoMap() {
	return explicitParameterInfoMap;
}
 
Example #29
Source File: RenderingContext.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Register parameters explicitly encountered in the criteria query.
 *
 * @param criteriaQueryParameter The parameter expression
 *
 * @return The JPA-QL parameter name
 */
ExplicitParameterInfo registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter);
 
Example #30
Source File: ParameterRegistry.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Registers the given parameter with this regitry.
 *
 * @param parameter The parameter to register.
 */
public void registerParameter(ParameterExpression<?> parameter);