Detachedcriteria and criteria for use and their differences!

Source: Internet
Author: User
Tags stringbuffer

In the conventional web programming, there are a lot of dynamic condition query, that is, the user freely select certain conditions on the page, the program according to the user's choice of conditions, dynamic generation of SQL statements, query.

For this requirement, for layered applications, the web layer needs to pass a list of criteria for a query to the business Layer object, after the business Layer object obtains the list of conditions, and then sequentially takes out the condition and constructs the query statement. One of the difficulties here is what the condition list constructs. The traditional use of map, but this approach is very flawed, the map can pass the information is very limited, can only pass the name and value, can not communicate what exactly to do the conditional operation, is greater than, less than, like, or something else, The business Layer object must have an exact grasp of the implied conditions of each entry. Therefore, once the implied conditions are changed, the query construction algorithm of the business Layer object must be modified, but the change of the query condition is implicitly agreed, rather than the program code constraint, so it is very error-prone.

Detachedcriteria can solve this problem, that is, on the web layer, programmers use Detachedcriteria to construct query conditions and then pass this Detachedcriteria as a method call parameter to the business Layer object. But after the business Layer object obtains the Detachedcriteria, may construct the criteria directly in the session scope, carries on the inquiry. In this case, the construction of the query statement is completely removed to the web layer implementation, and the business layer is only responsible for the completion of the persistence and query encapsulation, and query conditions constructed completely decoupled, very perfect.


The main difference between criteria and Detachedcriteria is that the form is created differently, the criteria is online, so it is created by the hibernate session, and Detachedcriteria is offline, Without a session at creation time, Detachedcriteria provides 2 static methods Forclass (Class) or Forentityname (Name) for Detachedcriteria instance creation.
The spring Framework provides a gethibernatetemplate (). Findbycriteria (Detachedcriteria) method to easily return query results based on Detachedcriteria.

Criteria:
Check all the data in the user table:
Criteria criteria = Session.createcriteria (User.class);
Check all the user's slots.
List users = Criteria.list ();
Iterator iterator = Users.iterator ();
while (Iterator.hasnext ()) {
User user = (user) iterator.next ();
System.out.println (User.getid () + user.getname ());
}

Hibernate actually uses the following SQL to find out:
Select This_.id as id0_, this_.name as name0_0_ from user This_

The criteria is only a container, and if you want to set up a search term, use the Add () method to add the restrictions condition, such as the data that is older than 20 and less than 40:
Criteria criteria = Session.createcriteria (User.class);
Criteria.add (restrictions.gt ("Age", New Integer (20));
Criteria.add (restrictions.lt ("Age", new Integer (40));
List users = Criteria.list ();

You can also use a logical group to conduct a search, such as a condition where the age is equal to (EQ) 20 or (or) is empty (IsNull):
Criteria criteria = Session.createcriteria (User.class);
Criteria.add (Restrictions.or (
Restrictions.eq ("Age", New Integer (20)),
Restrictions.isnull ("Age")
));
List users = Criteria.list ();



Detachedcriteria's associated query:

Suppose you want to query a student student record through Stuname, as follows:

Detachedcriteria DC = Detachedcriteria.forclass (Student.class);
Dc.add (Restrictions.like ("Stuname", Stuname, Matchmode.anywhere));

If you want to query a student record through the student team's teamname, many people will write this:
Detachedcriteria DC = Detachedcriteria.forclass (Student.class);
Dc.add (Restrictions.like ("Team.teamname", Teamname, Matchmode.anywhere));

Unfortunately, the above program error, said is not found in the student Team.teamname attribute, this is understandable. So how do you find student through Teamname?
You can write this:
Detachedcriteria DC = Detachedcriteria.forclass (Student.class);
Dc.createalias ("Team", "T");
Dc.add (Restrictions.like ("T.teamname", Teamname, Matchmode.anywhere));
Yes, you have to set up a team reference before you can navigate to teamname with the team.

Here's a special case, if you are querying the ID of a reference object, you can do without establishing a reference, that is, you can not call the CreateAlias () statement, as follows:
Detachedcriteria DC = Detachedcriteria.forclass (Student.class);
Dc.add (Restrictions.like ("Team.id", Teamid, Matchmode.anywhere));
According to my personal experience, the team can only follow its primary key properties, comparing other properties with aliases. This primary key attribute can be referred to by the "id" character, or it can be referred to by the primary key property of the team. In other words, my student class primary key "Stuid", whether in hql or in QBC, can be stu.id to refer to Stu.stuid. Here you can see the specificity of the "id" character. This is a personal point of view and has not been confirmed.


Detachedcriteria:

Example 1: If every beauty has its own client resources (don't think it's crooked.) , then you need to inquire about the beauty of customer gates.
Two ways:
1:
Detachedcriteria Beautycriteria = Detachedcriteria.forclass (Beauty.class). Createcriteria ("Customers");
Beautycriteria.add (Restrictions.eq ("name", "Gates")):

2:
Detachedcriteria Beautycriteria = Detachedcriteria.forclass (Beauty.class). CreateAlias ("Customers", "C");
Beautycriteria.add (Restrictions.eq ("C.name", "Gates")):

Then there are new requirements, too old beauty do not, or to find a customer gates, the conditions are as follows:
Detachedcriteria Beautycriteria = Detachedcriteria.forclass (Beauty.class, "B").;
Detachedcriteria Customercriteria = Beautycriteria.createalias ("Customers", c);
Beautycriteria.add (Restrictions.le ("B.age", New Long (20)):
Customercriteria.add (Restrictions.eq ("C.name", "Gates")):

For more detailed information on the criteria, Hibernate's source code and testing are the best documentation.
The disadvantage of the criteria. The DBA is angry and the consequences are serious.


Example 2:

Department and employee are One-to-many associations, and the query criteria are:
The name is "department" development Department;
The employees in the department are older than 20 years;


Detachedcriteria Detachedcriteria = Detachedcriteria.forclass (Department.class);
Detachedcriteria.add (Restrictions.eq ("name", "department"))
. CreateAlias ("Employees", "E")
. Add (Restrictions.gt ("E.age"), New Integer (20));


List List = This.gethibernatetemplate (). Findbycriteria (Detachedcriteria);

[Java] view plain copy detachedcriteria.add (expression.like ("Citycode", Markuplayer8.getcitycode (), Matchmode.anywhere));

Sql:java code if (startdate!=null &&!startdate.equals ("") && enddate!=null &&!enddate.equals (""                ) {StringBuffer sb = new StringBuffer ();                Sb.append ("EndDate >= '" + EndDate + "' and '" +startdate+ "' <= startdate");            Detachedcriteria.add (Expression.sql (sb.tostring ())); } list<markuplayer8> markuplayerlist = This.gethibernatetemplate (). Findbycriteria (DetachedCriteria);[Java]View plain Copy if (Startdate!=null &&!startdate.equals ("") && enddate!=null &&!enddate.equals (""))               {StringBuffer sb = new StringBuffer ();               Sb.append ("EndDate >= '" + EndDate + "' and '" +startdate+ "' <= startdate");           Detachedcriteria.add (Expression.sql (sb.tostring ())); } list<markuplayer8> markuplayerlist = This.gethibernatetemplate (). Findbycriteria (DetachedCriteria);



A full example: http://blog.csdn.net/kjfcpua/archive/2009/06/21/4287248.aspx 1. Create a criteria instance Org.hibernate.Criteria interface represents a query for a particular persisted class. The session is the factory for the criteria instance. Criteria crit = Sess.createcriteria (Cat.class); Crit.setmaxresults (50);    List cats = Crit.list (); 2. Limit result set content a separate query condition is an instance of the Org.hibernate.criterion.Criterion interface.

The Org.hibernate.criterion.Restrictions class defines a factory method that obtains some of the 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 grouped logically.

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", "Pk"})

. 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 a considerable number of built-in criterion types (restrictions subclasses), but it is particularly useful to allow

You 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 by the column alias of the entity being queried.

The property instance is another way to get a condition. You can create one by calling Property.forname ()

property.

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", "Pk"})

. List ();

3. Result set Ordering

You can use Org.hibernate.criterion.Order to sort the 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 ();

Note that the second Createcriteria () returns a new criteria instance that references the elements in the Kittens collection.

Next, the substitution pattern is also useful in some cases.

List cats = Sess.createcriteria (Cat.class)

.

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.