Skip to main content

JPA Tip #1 - Native Queries

Posted by mriem on August 22, 2007 at 11:30 AM PDT

OK, native queries in JPA. Not really well documented. Of course I understand that we really should not be doing that, but hey there are times where it is just plain easier.

The following code snippet goes after an Oracle sequence and gets the value.

EntityManager em = this.getEntityManager();
Query query = em.createNativeQuery("SELECT BLOG_ITEM_SEQ.nextval FROM DUAL");
Vector blogItemRow = (Vector) query.getSingleResult();
Integer blogItemId = (Integer) blogItemRow.elementAt(0);

As you can see by reading the Java code if you do a native query you
can map the result to a Vector and then for each row you have a Vector
for all the columns. In this particular case only one and the first column is an Integer.

Related Topics >>

Comments

So, for a multi-column,

So, for a multi-column, multi-row resultset, a couple of questions:
1. How does the method call on the query object change? From getSingleResult() to ??? (I could look at the API but I'm way too lazy for that! ;) )
2. What is the picture for this type of resultset in a vector? Something like:
row1: [col1] [col2] [col3]
row2: [col1] [col2] [col3]
row2: [col1] [col2] [col3]
So, to get col2 from row2, it would be blogItemRow.elementAt(4)? Or would it be more like a multi-dimensional array? It's been too long since I've studied the Collections API. Is Vector still backed by an array?
I've been in management too long! I need to get back in the game! ;)