请帮我一下。我已经读了大约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;
然后用
<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进行的这种联接。你能帮助我吗 ?
尝试使用此代码段,但出现错误
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:在类型ru.r1k0.spring.model.NewsCategoryDict上找不到“已创建”属性
最佳答案
假设您要返回与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
记录。