开发者

Efficently display results from multiple joins

In a JPA project I need to display a table whose data comes from 5 related entities. Without JPA I could write a sql query which joins the 5 database tables together and filters according开发者_JS百科 to some criteria. Suppose that the fields involved in the filtering criteria are only those of the first entity. Using JPA I can load filtered instances of the first entity and navigate through the properties till the final entity. My concern is that way the number of queries to the database can explode if I cannot use or do a mistake with the fecttype=eager annotation. Which is the best approach in such cases ? I would like to have a strict control over the sql queries that will be executed, so I can optimize them, but if I write the sql query with the joins by hand do I have to use the 'old' resultset to retrive the data ?


You can use JPA's built-in query language, the JPQL, can't you? (It does have a JOIN operator for sure.) Be aware though that this is not standard SQL, only something similar, so read the JPQL docs thoroughly. Yes, this is still plain text queries embedded in Java code, which is a shame, but hey, that's how far Java can go supporting the development process.

The main advantage here is that you get entity objects as the result of your queries - although you still need to cast them from Object. You can also use the objects (records) and their member variables (attributes) directly in the query string, so this is a step up from good old JDBC.

Alternatively you could also choose the Criteria API, but frankly, my experiences were not very good with it. The syntax is quite horrible and you basically end up building the low-level query yourself. This is clearly Java at its worst... but at least Strings containing queries can be eliminated from the code. I'm not sure it's worth it though.

Check this page for more information and examples:

http://download.oracle.com/javaee/6/tutorial/doc/gjise.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜