Hibernat uses criteria to query multiple-to-multiple relationship (SET) Conditions

Source: Internet
Author: User
Hibernate provides hql to facilitate the compilation of queries. But in some cases, I prefer criteria because its semantics is very clear.
When processing object association, it is often necessary to impose conditions on a set field under the object. For example, the following class:
Public class mainclass
{
Protected long ID;
Protected int type;
Protected set <subclass>
Subs = new hashset <subclass> ();
... Getter/setter
}
Public class subclass
{
Protected long ID;
Protected int value;
Protected set <mainclass> MS = new hashset <mainclass> ();
... Getter/setter
}
In the initialization data, assume that instance M1 of mainclass contains instances S1, S2, S3 of subclass, and instance m2 of mainclass contains instances S2, S3, and S4 of subclass.
The values of S1, S2, S3, and S4 are respectively 1, 2, 3, 4.
To query the mainclass instance whose subclass set contains subclass whose value is 2 and whose type is 1, you can use the following query method:
Detachedcriteria criteria = detachedcriteria. forclass (mainclass. Class );
Criteria
. Add (restrictions. eq ("type", new INTEGER (1 )))
. Createalias ("Subs", "S ")
. Add (restrictions. eq ("S. Value", new INTEGER (2 )));
After the query object is executed, a qualified mainclass instance is obtained.
Note that in the obtained mainclass instance, subs is a complete record set, rather than a filtered record set, which is equivalent to a complete Instance obtained based on the mainclass ID.
PS:
If you need to filter the subs record set, you need to use additional filtering methods. See the specific implementation of hibernate.
Hql can also be easily implemented, but the complete join mark must be provided, which is not as intuitive as createalias.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.