Sunday, November 23, 2014

NetBeans Tip: Working with JPQL

Have you heard of the NetBeans JPQL tool?  This is an often overlooked feature of NetBeans IDE that can save developers a lot of time.

If you are a Java EE developer, then you've likely encountered moments when you would like to see the results of a Java Persistence Query Language (JPQL) query before you've written your session bean method.  Being that I come from a database administrator background, I am oftentimes finding myself at the SQL command-line (or NetBeans SQL Editor) writing queries, and then translating the SQL into JPQL.  NetBeans IDE contains a JPQL tool (since NetBeans 7.3), which makes it easy to write JPQL queries and retrieve results immediately.  Let's see how:

The JPQL tool can be invoked within the context of a NetBeans project.  The project must have a valid Persistence Context, meaning that it is wired up for database access.  Once this is in-place, simply right click on the persistence.xml file, and click on the "Run JPQL Query" to open the tool.





















The tool provides a nice editor that provides a top pane for entering a query, and a bottom pane for showing the SQL or the results of the query execution.  If you have more than one Persistence Context within your persistence.xml, then you will have the option to select which context you would like to utilize for the query.












To execute the JPQL, simply click on the button next to the Persistence Context pull-down, or right click in the query editor and choose "Run JPQL".

The tool comes in super handy when you are executing queries that involve more than one entity.













Another handy reference for the tool, Geertjan's blog post:
https://blogs.oracle.com/geertjan/entry/test_jpql_with_netbeans_ide

Note:  Be sure to "Build" your project successfully before trying to use the JPQL tool.  If you do not have a successful build, you will likely encounter an error stating that the abstract schema type cannot be found:

No comments:

Post a Comment

Please leave a comment...