Well, I'm not going to be able to code your entire Hibernate Criteria API query, but I'll try to point you in the right direction.
One thing you'll definitely be interested in is the MatchMode:
Quote:
The MatchMode class has four properties that allow you to set the fuzzy matching facilities for an Example instance. The default is EXACT, while ANYWHERE is the most generous. END and START are bookend properties that only allow matches at the front or at the end of a given property.
static MatchMode ANYWHERE
Match the pattern anywhere in the string
static MatchMode END
Match the end of the string to the pattern
static MatchMode EXACT
Match the entire string to the pattern
static MatchMode START
Match the start of the string to the pattern
From there, you'll probably want to create an Example object, which is my favorite way of using the Criteria API, although you may find using the Restrictions class more to your liking. Here's a sample User query with the Criteria API, using the MatchMode feature as well:
Code:
User user = new User();
user.setPassword("PASS");
Example example = Example.create(user);
example.enableLike(MatchMode.ANYWHERE);
example.ignoreCase();
example.excludeProperty("verified");
Then to actually pull everything together, you'll see Hibernate3 code using the Criteria API that looks like this:
Code:
Session session = HibernateUtil.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
criteria.add(example); List results = criteria.list();
for (int i = 0; i<results.size(); i++) {
System.out.println(results.get(i).toString());
}
HibernateUtil.commitTransaction();
As I said, you might find the Restrictinos class more to your liking. Here's an example that looks for all users with an id of greater than 5, using a gt Restriction:
Code:
Session session = HibernateUtil.beginTransaction();
Criteria criteria =
session.createCriteria(User.class);
criteria.add(Restrictions.gt("id", 5));
List results = criteria.list();
HibernateUtil.commitTransaction();
for (int i = 0; i<results.size(); i++) {
System.out.println(results.get(i).toString());
}
Hopefully this will give you some ideas of how the Hibernate Criteria API can make your life a little easier when it comes to SQL and HQL queries.
Most of these examples were taken from the following tutorial on using the Hiberante Criteria API:
http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=09howtousethecriteriaapi
Check it out if you're interested in more examples and tutorials on Hibernate and using JPA, the Java Persistence API.