Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA select query with where clause

Tags:

java

jpa

I want to write a select statement but can't figure out how to write the where clause...

My code:

CriteriaQuery query = entityManager.getCriteriaBuilder().createQuery();
query.select(query.from(SecureMessage.class)).where();

This is within a method that I am passing a string to. I want to fetch only the rows that match the value of the string that Im passing to the method.

like image 973
mixkat Avatar asked Feb 27 '11 22:02

mixkat


2 Answers

In Criteria this is something like:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<SecureMessage> query = cb.createQuery(SecureMessage.class);
Root<SecureMessage> sm = query.from(SecureMessage.class);
query.where(cb.equal(sm.get("someField"), "value"));

In JPQL:

Query query = entityManager.createQuery("Select sm from SecureMessage sm where sm.someField=:arg1");
query.setParameter("arg1", arg1);

See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Criteria_API_.28JPA_2.0.29

like image 106
James Avatar answered Sep 28 '22 08:09

James


As I understand, the method parameter should be the parameter of the query.

So, should looks like:

Query query = entityManager.getCriteriaBuilder().createQuery("from SecureMessage sm where sm.someField=:arg1");
query.setParameter("arg1", arg1);

where arg1 - your method String parameter

like image 24
sergionni Avatar answered Sep 28 '22 10:09

sergionni