![](/img/trans.png)
[英]Trouble formulating a sql query in DAO Implementation using EntityManager.createQuery
[英]Trouble with EntityManager Query
由於某種原因,從方法運行此方法時未得到結果。
@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函數會在查詢時停止運行。 它不會拋出任何錯誤,只是停止。 我沒有主意,應該去哪里看? (其他具有count和select的類似方法都可以正常工作)。
使用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*/
您只能在em.createQuery()中傳遞JP-QL。 但是似乎您正在使用帶有r.RATING,r.POINT_ID之類的值的本機SQL,該值可能不在Java實體中。 將其替換為等效的Java實體變量,可以為pointId
em.createQuery("Select AVG(r.RATING) from Ratings r WHERE r.POINT_ID = :point");
如果要使用本機sql,則可以使用em.createNativeQuery()。
此問題最有可能是由大寫鎖定的屬性名稱引起的: RATING
, POINT_ID
。
嘗試用在Ratings
類中使用的替代它們,可能是:
Select AVG(r.rating) from Ratings r WHERE r.point.id = :point_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.