My original problem was https://stackoverflow.com/questions/12172614/hql-join-without-foreign-key-reference
but couldn't find any solution for this, hence moved forward with native query using JPA. createNativeQuery of entityManager returns Query object which in turn returns List<Object[]>
. I don't want to deal with indexes while iterating the list because it's error prone in nature.Therefore i looked at some other solution for it and found JPQL's Constructor expressions as one of the solution.
Table structure is
Schema1 -TableA
- NameColumn
- PhoneColumn
Corresponding Java class is
public class PersonSearch implements Serializable {
public PersonSearch (String NameColumn, String PhoneColumn) {
this.name = NameColumn;
this.phone = PhoneColumn;
}
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Query is
Select NEW com.xyz.PersonSearch(ms.NameColumn, ms.PhoneColumn) From Schema1.TableA ms Where ms.PhoneColumn='9134409930'
while running this query using entityManager API
entityManager.createQuery(queryString, PersonSearch.class);
getting below error.
Caused by: org.hibernate.hql.ast.QuerySyntaxException: Schema1.TableA is not mapped [Select NEW com.xyz.PersonSearch(ms.NameColumn, ms.PhoneColumn) From Schema1.TableA ms Where ms.PHONE='9134409930']
What's wrong with my code? Any idea ?
according to the book "Pro EJB 3 Java Persistence API"
Constructor Expressions
The example code is as follows
The EmpMenu class is a simple pojo, no annotations but has the correct constructor to match the constructor expression. The result is a List of EmpMenu objects for each row returned.
I believe the part of your SQL ".... From Schema1.TableA ms .." should refer to an entity that is mapped. So you should have an entity mapped to TableA, and then the jpql should be something more along the lines of ".... From MyTableAEntity ms ..." where MyTableAEntity has all the proper jpa annotations mapping it to DB table TableA. As the book snippet states, the target of "SELECT NEW ..." does not have to be mapped, but the entity referred to in the FROM clause does.