出于某种原因,从方法运行时我没有得到结果。
@SuppressWarnings("unchecked")
public Object[] getPointRaiting(Long id) {
EntityManager em = createEntityManager();
em.getTransaction().begin();
Query allPointsQuery = em
.createQuery("Select AVG(r.RATING) from Ratings r WHERE r.POINT_ID = :point");
allPointsQuery.setParameter("point", id);
Object[] rating = (Object[]) allPointsQuery.getSingleResult();
em.getTransaction().commit();
em.close();
closeEntityManager();
return rating;
}
SQL应该是正确的,因为它在HSQL数据库管理器中执行并返回正确的值。但java函数在查询时停止运行。它不会丢失任何错误。我没有想法,我应该在哪里看? (其他类似的计数和选择方法都正常工作)。
使用HSQLDB和Hibernate。
发现引发了以下错误:
org.hibernate.QueryException: could not resolve property: RATING of: kaart.entities.Ratings [Select AVG(r.RATING) from kaart.entities.Ratings r WHERE r.POINT_ID = :point]
但是这并没有解决它,因为RATING属性是在表和实体中定义的......
@Entity @Table(name = "RATINGS")
public class Ratings implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Point point;
@ManyToOne
private User user;
@Column(name = "RATING")
private int rating;
private static final long serialVersionUID = 1L;
public Ratings() {
super();
}
public Ratings(Point point, User user, int rating) {
this.point = point;
this.user = user;
this.rating = rating;
}
/*all getters and setters here*/}
@Entity
@Table(name = "POINT")
public class Point implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "point")
private List<Category> pointsByCategory;
@OneToMany(mappedBy = "point")
private List<Ratings> pointRatings;
@Column(name = "NAME")
private String name;
@Column(name = "LOCATION")
private String location;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "LINK")
private String link;
@ManyToOne
private User user;
private static final long serialVersionUID = 1L;
public Point() {
super();
}
public Point(String name, String location, String description, String link, User user) {
this.name = name;
this.location = location;
this.description = description;
this.link = link;
this.user = user;
} /* getters and setters*/
答案 0 :(得分:2)
你只能在em.createQuery()中传递JP-QL。 但似乎您使用的本机SQL的值如r.RATING,r.POINT_ID,可能不在Java实体中。将其替换为等效的java实体变量,可以是pointId
em.createQuery("Select AVG(r.RATING) from Ratings r WHERE r.POINT_ID = :point");
如果要使用本机sql,可以使用em.createNativeQuery()。
答案 1 :(得分:1)
此问题很可能是由大写锁定的属性名称引起的:RATING
,POINT_ID
。
尝试将其替换为Ratings
类中使用的那些,可能是:
Select AVG(r.rating) from Ratings r WHERE r.point.id = :point_id