|
Equal Restriction
The following example shows how to use Hibernate Equal restriction.
Refer first example for the configuration and mapping.
|
package com.bethecoder.tutorials.hibernate.basic.criteria;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class CriteriaEqualRestrictionTest {
/**
* @param args
*/
public static void main(String[] args) {
getCompaniesById(2);
getCompaniesByName("ABC");
}
private static void getCompaniesById(int id) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Company.class);
criteria.add(Restrictions.eq("id", new Integer(id)));
List<Company> companies = criteria.list();
System.out.println("Selected row count : " + companies.size());
for (Company company : companies) {
System.out.println(company);
}
session.getTransaction().commit();
session.close();
}
private static void getCompaniesByName(String name) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Company.class);
criteria.add(Restrictions.eq("name", name));
List<Company> companies = criteria.list();
System.out.println("Selected row count : " + companies.size());
for (Company company : companies) {
System.out.println(company);
}
session.getTransaction().commit();
session.close();
}
}
|
| |
It gives the following output,
Selected row count : 1
{ id = 2, name = ABC, employeeCount = 23430,
projectCount = 160, address1 = add11, address2 = add22 }
Selected row count : 1
{ id = 2, name = ABC, employeeCount = 23430,
projectCount = 160, address1 = add11, address2 = add22 }
|
|