Choose from two tables using JPQL

I use JPQL to retrieve data. I can get data using a statement

 List persons = null; persons = em.createQuery("select p.albumName from PhotoAlbum p , Roleuser r where r = p.userId and r.userID = 1"); 

Now I can get the album names using this:

 int i=0; for (i=0;i<persons.size(); i++) { System.out.println("Testing n "+ i +" " + persons.get(0)); } 

Now I want to get the album name and the roleuser string named firstname

I am using a request

 persons = em.createQuery("select r.firstName , p.albumName from PhotoAlbum p , Roleuser r where r = p.userId and r.userID = 1").getResultList(); 

Now how to get the firstname and albumname strings when person.get (0) returns an object

by running the code:

  for (i=0;i<persons.size(); i++) { //r = (Roleuser) persons.get(i); System.out.println("Testing n "+ i +" " + persons.get(i)); } 

I get this:

 Testing n 0 [Ljava.lang.Object;@4edb4077 INFO: Testing n 1 [Ljava.lang.Object;@1c656d13 INFO: Testing n 2 [Ljava.lang.Object;@46dc08f5 INFO: Testing n 3 [Ljava.lang.Object;@654c0a43 

How to match persons.get(0) and get firstname and albumname ?

+4
source share
1 answer

Now how to get the firstname and albumname strings when person.get (0) returns an object

Queries with multiple select_expressions in a SELECT clause return Object[] (or a List of Object[] ). From the JPA specification:

4.8.1 Result SELECT clause type

The type of the specified query result at the suggestion of the SELECT query is the type of abstract entity schema, and the type of the state field, the result is an aggregate function, the result of construction, or their sequence.

The result type of the SELECT clause is determined by the result types of the select_expression contained in This. When multiple select_expressions are used in a SELECT clause, the query result is of type Object[] , and the elements in this result correspond to the order in the order of their specification in the SELECT clause and in type to the result types of each of the select_expressions.

So, in your case, you probably want something like this:

 for (i=0;i<persons.size(); i++) { //r = (Roleuser) persons.get(i); System.out.println("Testing n " + i + " " + persons.get(i)[0] + ", " + persons.get(i)[1]); } 

Note that specifying an inner join using a Cartesian product in the FROM clause and a join condition in the WHERE clause is less typical than specifying an explicit join over an entity (using the syntax [LEFT [OUTER] | INNER ] JOIN ). See Entire Section 4.4.5 Consolidation in the specification.

References

  • JPA 1.0 Specification
    • Section 4.8.1 "Result Type of SELECT Clause"
    • Section 4.8.2 "Constructor Expressions in the SELECT Section"
    • Section 4.4.5 "Joins"
+7
source

All Articles