我无法使此查询有效:
Query query = eManager.createQuery("select c FROM News c WHERE c.NEWSID = :id",News.class);
return (News)query.setParameter("id", newsId).getSingleResult();
我得到了这个例外:
Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].
[27, 35] The state field path 'c.NEWSID' cannot be resolved to a valid type.] with root cause
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].
为什么会这样? :id和命名参数相同
修改 我的实体类
@Entity
@Table(name="NEWS")
public class News implements Serializable{
@Id
@SequenceGenerator(name = "news_seq_gen", sequenceName = "news_seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq_gen")
private int newsId;
private String newsTitle;
private String newsBrief;
private String newsContent;
private Date newsDate;
@Transient
private boolean selected=false;
//constructor and getters and setters
答案 0 :(得分:18)
这是因为News
实体没有名为NEWSID
的持久属性。持久属性的名称在JPQL查询中区分大小写,并且应该使用与它们在实体中出现的完全相同的大小写。
因为实体具有名为newsId
的持久属性,所以也应该在查询中使用,而不是NEWSID
:
select c FROM News c WHERE c.newsId = :id
答案 1 :(得分:0)
实体具有名为newsId的持久属性。但在查询中,您使用了NEWSID。试试这个
select c FROM News c WHERE c.newsId = :id
答案 2 :(得分:-1)
我的实体是:
@Entity
@Table(name = "TBL_PERSON_INFO")
public class Person implements Serializable {
@Id
@Column(name = "ID", nullable = false)
private Integer id;
@Column(name = "USER_ID", nullable = false)
private Integer user_id;
.
.
.
}
我的查询是(JPQL):
String queryName = "from Person p where p.user_id = :user_id";
所以我这样使用它:
javax.persistence.Query query = em.createQuery(queryName);
query.setParameter("user_id", userId);
try {
obj = query.getSingleResult();
}
catch (javax.persistence.NoResultException nre) {
logger.error("javax.persistence.NoResultException: " + nre.getMessage());
}
catch (javax.persistence.NonUniqueResultException nure) {
logger.error("javax.persistence.NonUniqueResultException: " + nure.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
if (obj == null) {
System.out.println("obj is null!");
return null;
}
Person person = (Person) obj;
这是工作; - )