Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Query Using @NamedQuery with a 'SELECT OBJECt(var) FROM EntityName var

I have started to learn JPA and I have searched on many sites and I couldn't find an explanation regarding this example :

Implementing a Query Using @NamedQuery:

   @Entity
   @NamedQuery(
    name="findAllEmployeesByFirstName",
    queryString="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = 'John'"
)
public class Employee implements Serializable {
...
}

I just can't understand why the author is selecting an Object(emp)..why doesn't he use something like this SELECT emp FROM Employee emp WHERE emp.firstName = 'John'

Is there a difference ? Do I miss something ?

like image 786
Andreea Avatar asked Mar 11 '23 16:03

Andreea


2 Answers

SELECT OBJECT(emp) FROM Employee emp

is the exact same as

SELECT emp FROM Employee emp

See the JPA spec. [69] Note that the keyword OBJECT is not required. It is preferred that it be omitted for new queries.

The origin of "OBJECT" is in EJBs (now outdated).

like image 93
Neil Stockton Avatar answered Apr 19 '23 03:04

Neil Stockton


The difference is that even though path expressions can resolve to an entity type, the syntax of the OBJECT keyword is limited to identification variables.

You can safely remove OBJECT from the query.

To make an example, if Employee has a relationship with a Department entity, this query would be illegal using object:

SELECT OBJECT(emp.department) FROM Employee emp WHERE emp.firstName = 'John'  // Not valid
SELECT emp.department FROM Employee emp WHERE emp.firstName = 'John' // Valid
like image 20
David SN Avatar answered Apr 19 '23 02:04

David SN