简体   繁体   中英

Hibernate Query for ManyToMany Relationship

A bit of disclaimer:

  • I am at beginner level in Java
  • I am beginner level at hibernate

Ok, since we have got that out of the way, my question is the following:

My EmailAddressModel has the below mapping to EmailAddressTag

private String id;
@Column(unique = true)
private String emailAddressName;

@ManyToMany(fetch = FetchType.EAGER)
private Set<EmailAddressTag> emailAddressTags = new HashSet<EmailAddressTag>();

and my EmailAddressTag is:

private String id;    
@Column(unique = true)
private String emailAddressTags;

Sample data set:

id: 1
emailAddressName: abc@gmail.com
tags (id=1,emailAddressTags=tag1)

How can I construct a query to fetch an Email address knowing the tag (the entire object) using HQL. Something like

select * from EmailAddressTable where EmailAddressTable.Tag = 'tag1'

I have tried:

Set<EmailAddressTag> listOfTags = new HashSet<EmailAddressTag>();
listOfTags.add(tagToSearch);
Query query = session.createQuery("FROM EmailAddressTable item WHERE item.Tag IN (:tags)");
query.setParameterList("tags", listOfTags)

But, the error (java error) I have if use setParameterList is

Cannot cast ...EmailAddressTag to java.util.Collection

And the error (hibernate error) I have if use setParameter is

malformed numeric constant: .

Any help I will truly appreciate. Really lost here.

You should be able to fix the compiler error, if you actually use a collection for the listOfTags variable. You did not show that part of the code, but it could look something like this:

Set<EmailAddressTag> listOfTags = new HashSet<EmailAddressTag>();
listOfTags.add(tagToSearchFor);
...
query.setParameterList("tags", listOfTags);

If you want use setParameter() instead, you should be able to fix the hibernate error, if you change your query condition to only check for a single tag:

Query query = session.createQuery("FROM EmailAddressTable item WHERE item.Tag = :tag");
query.setParameter("tag", tagToSearchFor)

Hope this helps.

I have found an answer. Its as follows.

operator is AND or OR

String hql = String.format("FROM %s obj where 1=1 ",c.getSimpleName());
for (int i = 0; i < tempList.size(); i++) {
    hql += " "+operator+" :collection" + i + " = some elements(obj.emailAddressTags)";
}

Query query = session.createQuery(hql);
for (int i = 0; i < tempList.size(); i++) {
    query.setParameter("collection" + i, tempList.get(i));
}
list = query.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM