请帮我一下。我已经阅读了大约10篇文章,但不了解加入时刻。我有2张桌子:
public class News implements Serializable {
@Id
@GeneratedValue (generator = "increment")
@GenericGenerator (name = "increment", strategy = "increment")
private int id;
@Column
private String name;
@Column
private Date created;
@Column
private String data;
@ManyToOne (cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn (name = "category_id")
private NewsCategoryDict category;
// getters, setters
}
和
public class NewsCategoryDict implements Serializable {
@Id
@GeneratedValue (generator = "increment")
@GenericGenerator (name = "increment", strategy = "increment")
private int id;
@Column
private String name;
@OneToMany (mappedBy = "category", cascade = CascadeType.ALL)
private List<News> news = new ArrayList<>();
}
我希望查询的工作方式与
类似SELECT * FROM news, categorynews WHERE news.category_id = categorynews.id;
然后使用
在jsp中获得结果 <div id="list_news">
<c:forEach items="${news}" var="news">
<h5>${news.id} : ${news.name} - ${news.created} ; ${news.data} (${news.category.name})</h5>
</c:forEach>
</div>
我无法通过Criteria API理解这个JOIN。你能帮助我吗 ? 尝试使用此代码段,但收到错误
public List<News> getAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<News> cq = cb.createQuery(News.class);
Root<News> rootFromNews = cq.from(News.class);
Join<NewsCategoryDict, News> join = rootFromNews.join("category");
cq.select(join);
return em.createQuery(cq).getResultList();
}
PropertyNotFoundException:Property&#39; created&#39;在类型ru.r1k0.spring.model.NewsCategoryDict
上找不到
答案 0 :(得分:1)
您的错误与加入无关!实际发生的是,在JSP片段中,您尝试访问 NewsCategoryDict 中不存在的 $ {news.created} 。我相信错误发生在JSP片段中,而不是在Criteria查询中。
我理解它的方式是你要列出新闻对象,但在查询中你选择的是NewsCategoryDict,这就是为什么最后你最终会丢失属性,因为NewsCategoryDict不包含 $ {news.created}
答案 1 :(得分:1)
假设您要返回与News
实例关联的NewsCategoryDict
实例,您的条件查询应如下所示:
public List<News> getAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<News> cq = cb.createQuery(News.class);
Root<News> rootFromNews = cq.from(News.class);
Join<News, NewsCategoryDict> join = rootFromNews.join("category"); // #1
cq.select(rootFromNews); // #2
return em.createQuery(cq).getResultList();
}
修改后的行标有#1
和#2
条评论。
查询应返回匹配News
的所有NewsCategoryDict
;但不会返回与News
记录无关的NewsCategoryDict
条记录。