简体   繁体   中英

JPA select query with where clause

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM