Does anyone have a good example for how to do a findByExample in JPA that will work within a generic DAO via reflection for any entity type? I know I can do it via my prov
Maybe the answer is too late. But check this. It might be of help.
https://sourceforge.net/projects/simplejpaquery/
First, include the jar into the classpath. You will have a class called com.afifi.simpleJPAQuery.entities.utility.JPAUtil
.
This class uses reflection to deduct the query from the bean.
Suppose you have an entity bean as follows:
@Entity
public class Person {
@Id
private Integer personNo;
private String personName;
public Integer getPersonNo() {
return personNo;
}
public void setPersonNo(Integer personNo) {
this.personNo = personNo;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
Then if you want to query by person name for instance, you need to do as follows:
//initiate entity manager (em)
Person p=new Person();
p.setPersonName("John");
String sortString="";
List<Person> result= JPAUtil.findByExample(em,p,sortString);
The result will get all the records where the person name contained the word "John".
if you want to limit the results, you can do something like:
List<Person> result= JPAUtil.findByExample(em, p, sortString, start, size);
This library has other methods like:
getResultCount
: to get the count of the result
createSqlStatement
: to get the sql statement that is being used
getSqlWhereString
: to get just the where string used
It has the native forms of these functions:
findByExampleNative
, getResultCountNative
, createSqlStatementNative
and getSqlWhereStringNative
The library also has QueryAnnotations
class that contains annotations that can be added to the Entity bean properties to give more control on how you want to query using the bean.