简体   繁体   中英

Inject attribute into JPQL SELECT clause

Let's depict the following use case: I have a JPQL Query which on the fly creates data objects using the new keyword. In the SELECT clause I would like to inject an attribute which is not known to the database but to the layer which queries it.

This could look like

EntityManager em; // Got it from somewhere
boolean editable = false; // Value might change, e.g. depending on current date

Query q = em.createQuery("SELECT new foo.bar.MyDTO(o, :editable) FROM MyObject o")
            .setParameter("editable", editable);

List<MyDTO> results = (List<MyDTO>) q.getResultList();

Any ideas how this kind of attribute or parameter injection into the SELECT clause might work in JPQL? Both JPA and JPA 2.0 solutions are applicable.

Edit: Performance does not play a key role, but clarity and cleanness of code.

Have you measured a performance problem when simply iterating over the list of results and call a setter on each of the elements. I would guess that compared to

  • the time it takes to execute the query over the database (inter-process call, network communication)
  • the time it takes to transform each row into a MyObject instance using reflection
  • the time it takes to transform each MyObject instance into a MyDTO using reflection

your loop will be very fast.

If you're so concerned about performance, you should construct your MyDTO instances manually from the returned MyObject instances instead of relying on Hibernate and reflection to do it.

Keep is simple, safe, readable and maintainable first. Then, if you have a performance problem, measure to detect where it comes from. Then and only then, optimize.

It will not work without possible vendor extensions, because according specification:

4.6.4 Input Parameters
...
Input parameters can only be used in the WHERE clause or HAVING clause of a query.

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