开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜