ElementCollection createAlias in hibernate API

旧城冷巷雨未停 提交于 2019-12-03 10:41:54

Late answer.

The correct propertyName for collection (annotated by @ElementCollection) is "elements" or constant CollectionPropertyNames#COLLECTION_ELEMENTS.

Try with the following answers

Criteria crit = getSession().createCriteria(Discussion.class);
crit.createAlias("participants", "p");

crit.add(Restrictions.eq("p.elements", portalUsername));

or use the constant COLLECTION_ELEMENTS instead

crit.add(Restrictions.eq("p." + CollectionPropertyNames.COLLECTION_ELEMENTS, portalUsername));

As explained here what I wanted is not possible:

The limitations of using an ElementCollection instead of a OneToMany is that the target objects cannot be queried, persisted, merged independently of their parent object. They are strictly privately-owned (dependent) objects, the same as an Embedded mapping. There is no cascade option on an ElementCollection, the target objects are always persisted, merged, removed with their parent.

So, I used a OneToMany instead.

Can you give us a more complete schema and query?

Also, Criteria API sucks. Try using QueryDSL, your query might look like:

HibernateQuery q=new HibernateQuery(getSession())
.from(QDiscussion.discussion).from(QDocument.document)
.where(QDocument.document.userName.in(QDiscussion.discussion.userNames))
.list(QDocument.document);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!