In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces what is the use of Criteria in Hibernate. It is very detailed and has a certain reference value. Interested friends must finish reading it!
Now summarize the usage of Hibernate Criteria:
Hibernate designed CriteriaSpecification as the parent interface of Criteria, and Criteria and DetachedCriteria are provided below. The main difference between Criteria and DetachedCriteria is that the form of creation is different. Criteria is online, so it is created by Hibernate Session, while DetachedCriteria is offline and provides two static methods forClass (Class) or forEntityName (Name) to create DetachedCriteria instances without Session,DetachedCriteria. Spring's framework provides the getHibernateTemplate (). FindByCriteria (detachedCriteria) method to easily return query results based on DetachedCriteria.
Both Criteria and DetachedCriteria can use Criterion and Projection to set query criteria. You can set FetchMode (the mode of federated query fetching) and set the sort mode. For Criteria, you can also set FlushModel (how Session is flushed) and LockMode (database lock mode).
Hibernate Criterion and Projection are described in detail below.
Hibernate Criterion is the query condition of Criteria. Criteria provides an add (Criterion criterion) method to add query conditions.
The main implementations of Hibernate Criterion interface include Example, Junction and SimpleExpression. The actual use of Junction is its two subclasses, conjunction and disjunction, which use the AND and OR operators to join the set of query conditions. Instances of Criterion can be created through the Restrictions utility class. Restrictions provides a large number of static methods, such as eq (equal to), ge (greater than or equal to), between, etc., to create Criterion query conditions (SimpleExpression instances).
In addition, Restrictions provides methods to create conjunction and disjunction instances, adding query conditions to the instance's add (Criteria) method to form a set of query conditions. As for the creation of Example is different, Example itself provides a static method create (Object entity), which is created based on an object (which is usually mapped to a database in actual use). You can then set some filter criteria:
Example exampleUser = Example.create (u) .enabreCase () / / ignores case. EnableLike (MatchMode.ANYWHERE); / / A pair of attributes of type String, no matter where the values match. Equivalent to% value%
Project mainly enables Criteria to query reports and realize grouping. Project mainly has three implementations: SimpleProjection, ProjectionList and Property. The instantiation of SimpleProjection and ProjectionList is accomplished by the built-in Projections. For example, the provided avg, count, max, min and sum make it easy for developers to make statistical queries on certain fields. Property is the setting of query conditions for a field, such as through Porperty.forName ("color") .in (new String [] {"black", "red", "write"}); you can create an instance of Project. Pass through
The add (Project) method of criteria is added to the query condition. When querying with Criteria, it is important to make it clear which classes and methods are provided by Hibernate to satisfy the creation and assembly of query conditions in development. Here are several uses:
1. Create an instance of Criteria
The org.hibernate.Criteria interface represents a query for a specific persistent class. Session is the factory for Criteria instances.
Criteria crit = sess.createCriteria (Cat.class); crit.setMaxResults (50); List cats = crit.list ()
two。 Limit the content of the result set
A separate query condition is an instance of the org.hibernate.criterion.Criterion interface.
The org.hibernate.criterion.Restrictions class defines factory methods to get some built-in Criterion types.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.like ("name", "Fritz%")) .add (Restrictions.between ("weight", minWeight, maxWeight)) .list ()
Constraints can be logically grouped.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.like ("name", "Fritz%")) .add (Restrictions.or (Restrictions.eq ("age", new Integer (0)), Restrictions.isNull ("age") .list () List cats = sess.createCriteria (Cat.class) .add (Restrictions.in ("name", new String [] {"Fritz", "Izi", "competition"})) .add (Restrictions.disjunction () .add (Restrictions.isNull ("age")) .add (Restrictions.eq ("age", new Integer (0) .add (Restrictions.eq ("age") New Integer (1) .add (Restrictions.eq ("age", new Integer (2) .list ()
Hibernate provides quite a number of built-in criterion types (Restrictions subclasses), but it is particularly useful to allow you to use SQL directly.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.sql ("lower ({alias} .name) like lower (?)", "Fritz%", Hibernate.STRING)) .list ()
The {alias} placeholder should be replaced with the column alias of the entity being queried.
A Property instance is another way to get a condition. You can create a Property by calling Property.forName ().
Property age = Property.forName ("age") List cats = sess.createCriteria (Cat.class) .add (Restrictions.disjunction () .add (age.isNull ()) .add (age.eq (new Integer (0) .add (age.eq (new Integer (1) .add (age.eq (new Integer (2) .add (Property.forName ("name") ). In (new String [] {"Fritz" "Izi", "Competition"}) .list ()
3. Result set sorting
You can use org.hibernate.criterion.Order to sort query results.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.like ("name", "F%") .addOrder (Order.asc ("name")) .addOrder (Order.desc ("age")) .setMaxResults (50) .list () List cats = sess.createCriteria (Cat.class) .add (Property.forName ("name"). Like ("F%") .addOrder (Property.forName ("name"). Asc ()) .addOrder (Property.forName ("age"). Desc ()) .setMaxResults (50) .list ()
4. Association
You can use createCriteria () to easily establish constraints between interrelated entities.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.like ("name", "F%") .createCriteria ("kittens") .add (Restrictions.like ("name", "F%") .list ()
Notice that the second createCriteria () returns a new Criteria instance that references elements in the kittens collection.
Next, replacement forms are also useful in some cases.
List cats = sess.createCriteria (Cat.class) .createAlias ("kittens", "kt") .createAlias ("mate", "mt") .add (Restrictions.eqProperty ("kt.name", "mt.name")) .list ()
(createAlias () does not create a new instance of Criteria.)
The kittens collection returned by the previous two queries saved by the Cat instance is not conditionally pre-filtered. If you want to get only qualified kittens, you must use returnMaps ().
List cats = sess.createCriteria (Cat.class) .createCriteria ("kittens", "kt") .add (Restrictions.eq ("name", "F%")) .returnMaps () .list (); Iterator iter = cats.iterator (); while (iter.hasNext ()) {Map map = (Map) iter.next (); Cat cat = (Cat) map.get (Criteria.ROOT_ALIAS) Cat kitten = (Cat) map.get ("kt");}
5. Dynamic association crawling
You can use setFetchMode () to define the semantics of dynamic association fetching at run time.
List cats = sess.createCriteria (Cat.class) .add (Restrictions.like ("name", "Fritz%")) .setFetchMode ("mate", FetchMode.EAGER) .setFetchMode ("kittens", FetchMode.EAGER) .list ()
This query can grab mate and kittens through external joins.
6. Query example
The org.hibernate.criterion.Example class allows you to build a conditional query from a given instance.
The org.hibernate.criterion.Example class allows you to build a conditional query from a given instance. Cat cat = new Cat (); cat.setSex ('F'); cat.setColor (Color.BLACK); List results = session.createCriteria (Cat.class) .add (Example.create (cat)) .list ()
Version attributes, identifiers, and associations are ignored. Properties with a value of null by default are excluded.
You can adjust the Example to make it more practical.
Example example = Example.create (cat) .origindeZeroes () / / exclude zero valued properties .accoundeProperty ("color") / / exclude the property named "color" .returreCase () / / perform case insensitive string comparisons .enableLike (); / / use like for string comparisons List results = session.createCriteria (Cat.class) .add (example) .list ()
You can even use examples to place conditions on associated objects.
List results = session.createCriteria (Cat.class) .add (Example.create (cat)) .createCriteria ("mate") .add (Example.create (cat.getMate () .list ())
7. Projection (Projections), aggregation (aggregation), and grouping (grouping)
Org.hibernate.criterion.Projections is an example factory of Projection. We project to a query by calling setProjection ().
List results = session.createCriteria (Cat.class) .setProjection (Projections.rowCount ()) .add (Restrictions.eq ("color", Color.BLACK)) .list () List results = session.createCriteria (Cat.class) .setProjection (Projections.projectionList () .add (Projections.rowCount ()) .add (Projections.avg ("weight")) .add (Projections.max ("weight")) .add (Projections.groupProperty ("color") .list () The above is all the content of this article "what is the use of Criteria in Hibernate?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.