我是java ee和persistance技术的新手。
我正在尝试编写动态查询。细节:
有一个数据表(' newsactivites '),它看起来像这样:
id type
4 UploadVideo
4 CreateBlog
1 UploadPicture
10 UploadVideo
10 CreateBlog
此外还有一个枚举:
public enum Type {
UploadVideo("show.uploadedVideo"),
UploadPicture("show.uploadedPicture"),
CreateBlog("show.createdBlog");
}
所以我想写一个像这样的方法:
private List<Type> activities=new ArrayList<Type>();
@CollectionElements()
@Column(name="type")
@Enumerated(EnumType.STRING)
@JoinTable(name = "newsactivities", joinColumns = { @JoinColumn(name = "id") })
public List<Type> getActivities() {
return activities;
}
但我想在给定的时间回馈一个id的活动:
public List<Type> getActivities(int id) { }
非常感谢任何帮助!
答案 0 :(得分:0)
如果我正确地阅读了您的模型(我不确定),您应该拥有一个带有外键Newsactivities
的实体类Newsactivities.class
(在类type
中)。那么你需要List<Newsactivities>
(而不是List<Types>
):
public List<Type> getActivities(int id) {
TypedQuery<Newsactivities> tq = em.createQuery(
"SELECT n FROM Newsactivities n WHERE n.type=:type, Newsactivities.class);
tq.setParameter("type", id);
return(tq.getResultList());
}
答案 1 :(得分:0)
您与对象的Type
相关联,就像您写的那样:
public class A{
private List<Type> activities=new ArrayList<Type>();
@CollectionElements()
@Column(name="type")
@Enumerated(EnumType.STRING)
@JoinTable(name = "newsactivities", joinColumns = { @JoinColumn(name = "id") })
public List<Type> getActivities() {
return activities;
}
}
然后,您需要Repository
,如下所示:
public interface ARepository extends JpaRepository<A,Long>{
@Query("select a.activities from A a where a.id=?1")
List<Type> findTypeById(Long id);
}
现在,您可以使用findTypeById
,这要求您拥有A
对象