Reputation: 1763
I want to do a native SQL query, which joins 2 Tables.
The return value should be all elements of the District Table, which would be (id, name, district_code, coordinates)
, and also a count(*)
of all Objects which are in a District
(therefore the join with some other table).
So I have all columns of district (district.*)
one field which is Count(*)
.
Which kind of query can I use, so that I can comfortable use it in my java code? I can't add an entity or, because the count(*)
wouldn't fit to it!?
I have got a District class which looks like this:
@XmlRootElement
public class District extends AbstractEntity{
private int id;
private String name;
private int district_code;
@Transient
private int carsQuantity;
public District(){}
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDistrict_code() {
return district_code;
}
public void setDistrict_code(int district_code) {
this.district_code = district_code;
}
public int getCarsQuantity() {
return carsQuantity;
}
public void setCarsQuantity(int carsQuantity) {
this.carsQuantity = carsQuantity;
}
}
My District.hbm.xml:
<hibernate-mapping package="at.opendata.entitys">
<class name="District" table="districts">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="name"/>
<property name="district_code"/>
</class>
</hibernate-mapping>
EDIT:
I can't do it with HQL oder JPQL, because I need a SUBSELECT in my FROM CLAUSE.
SELECT d.id, count(*) FROM (SELECT cd.coordinates AS coordinates FROM cars AS c LEFT JOIN cardetail AS cd ON (c.car_id = cd.car_id)) AS c CROSS JOIN districts AS d WHERE ST_CONTAINS(d.coordinates, c.coordinates) GROUP BY id
Upvotes: 1
Views: 1433
Reputation: 691635
First of all, you don't need a native query for that. JPQL will do just fine. And the result of such a query will simply be a List<Object[]>
, where each object array will contain an element for each returned column. Just iterate over this list and do whatever you want with the elements:
for (Object[] row : list) {
Integer id = (Integer) row[0];
String name = (String) row[1];
...
Long count = (Long) row[4];
...
}
Upvotes: 1