Java Code Examples for javax.persistence.criteria.CriteriaBuilder#parameter()

The following examples show how to use javax.persistence.criteria.CriteriaBuilder#parameter() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Source File: SoftDeletesRepositoryImpl.java    From spring-boot-jpa-data-rest-soft-delete with MIT License 4 votes vote down vote up
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	Path<?> path = root.get(entityInformation.getIdAttribute());
	parameter = cb.parameter(Iterable.class);
	return path.in(parameter);
}