I'm using JPA for a project and in most cases, want to get entities, but there are a few cases (reporting being one of them, but there are others) where I do not want or need to get entities, but rather want a selection of values. Does JPA support this? If so, does it make sense to use it or does it make sense to use straight JDBC in these cases?
+7
A:
Q1: Yes, it does.
It's so called scalar queries, e.g.:
select u.name from User u
as opposed to
select u from User u
Q2: When it comes to sense of using it: Such queries have sense - you just simply need a single property not the whole object. But if you plan to make all your queries only fetching separate values, then the question 'why?' seems valid. The whole idea of O/R mappers is to allow you operate on objects, not (related) tables and ids. So fetching ids using JPA usually doesn't make sense. Once you have objects mapped to database, it should be easier for you to operate on the data.
Grzegorz Oledzki
2009-11-17 19:21:36
I'm looking to get multiple values. Is there a way to get u.name, u.age from User u? This is a simplified example and I'm not pulling multiple values from an entity. And I am mostly using JPA for entities, just wondering whether it makes sense to introduce something like JDBC for the those cases where I'm doing something different. I guess it is a threshold question.
Tim
2009-11-17 19:39:00
Obviously, as per the JPA spec. As you wrote it
DataNucleus
2009-11-17 21:02:42
A:
SQLResultsetMappingWithAlias at java2s.com seems to provide an example of what you are looking for.
Chris Kaminski
2009-11-17 19:22:04