gpt4 book ai didi

java - EntityManager 查询出现问题

转载 作者:行者123 更新时间:2023-12-01 23:00:08 26 4
gpt4 key购买 nike

出于某种原因,我在从方法运行此方法时没有得到结果。

@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*/

最佳答案

您只能在 em.createQuery() 中传递 JP-QL。但似乎您正在使用 native 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()。

关于java - EntityManager 查询出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com