Reputation: 235
I am working on a project where two entities have unidirectional @OneToMany mapping. When I tried to load all child entities for particular parent id with this query -
select p.childEntities from Parent p where p.id =:parentId
It works fine. Also note that here I am using hibernate api for pagination so I get only 10, 25 ... records. At many points I only need count of entities. Now I am trying to load only count of all child entities with this query-
select count(p.childEntities) from Parent p where p.id =:parentId
which fails with ORACLE error code - ORA-00936: missing expression
My situation(Low authority for this project)- I can not change the entity mappings into bidirectional. And No use of native SQL. Also I think that getting all list using -
" select p.childEntities from Parent p where p.id =:parentId "
and then just getting size() for count is performance costly.
A glimpse of mappings in project- Parent Class-
@Entity
@Table(name = "PARENT")
public class Parent implements Serializable{
private static final long serialVersionUID = 2232715856164345328L;
private Long id;
private String first;
private String second;
private String third;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
private List<Child> childEntities;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public List<Child> getChildEntities() {
return childEntities;
}
public void setChildEntities(List<Child> childEntities) {
this.childEntities = childEntities;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
And Child Class-
@Entity
@Table(name = "Child")
public class Child {
private Long id;
private Integer number;
private String prop1;
private String prop2;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
}
What all choices I am left with?
Upvotes: 0
Views: 1182
Reputation: 691953
You need to learn about joins (which is what you would also use in SQL, BTW):
select count(c.id) from Parent p join p.childEntities c where p.id = :parentId
Upvotes: 2