This discussion is archived
1 Reply Latest reply: Feb 8, 2013 7:01 AM by cdelahun RSS

JPA query by entity/object ?

989627 Newbie
Currently Being Moderated
I am trying to write an abstract API which dynamically assigns any Entity Class that needs to be persisted and retrieved using the Entity Manager.
Saving into the database is not a problem, I just do entityManager.save(Class) and it works for any class that needs to be persisted.
However, when querying for the object based upon the attributes, I want to avoid naming particular attributes and want to use the Entity class's attributes against itself for querying.
For example, the client program will say something like this to query by name and age of a Person:

-------calling (client) program: ---
Person p = << get from UI, not saved yet, no Id but has all other attributes like name and age etc. >>

List<Person> persons = dao.getAllThatMatch(p);
--- end client Program --

--- DAO class ---
List<T> getAllThatMatch(T t) {  //note that expectation is that returned is a list of Object which is the same as the querying object
List<T> entityList = em.someFinderMethod(t);
//the someFinderMethod method should automatically query for all Person objects that match the attributes provided by the object of Person supplied as criteria
//NOTE: there is no attribute mentioned extensively like name, age etc.
return entityList ;
}
-- end DAO class --

Edited by: user7626479 on Feb 6, 2013 3:55 PM

Edited by: user7626479 on Feb 6, 2013 3:55 PM
  • 1. Re: JPA query by entity/object ?
    cdelahun Pro
    Currently Being Moderated
    Query by example is not included in the JPA standard, but it is possible to do with EclipseLink.
    See http://wiki.eclipse.org/EclipseLink/Examples/JPA/ORMQueries#Query_By_Example
    for how to use query by example with native EclipseLink queries. To execute a native query through JPA, you will need to call createQuery(DatabaseQuery query) on the org.eclipse.persistence.jpa;JpaEntityManager obtained from the javax.persistence.EntityManager instance by calling getDelegate() or unwrap.

    Best Regards,
    Chris

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points