Hibernate Ders 14 – Criteria Queries – 02

Merhaba Arkadaslar,
Bu dersimizde bir onceki ornegimiz uzerinden devam edecegiz Disjunction Criteria, SQLRestriction, Paging Criteria, Order Criteria gibi Restriction durumlarina karsilik gelen metotlari isleyecegiz.

Bir onceki ornegimizde or mantigini kullanmistik peki ya birden fazla or gerekirse ?  SQL den hatirlayacagimiz in yapisina uygun bir yapiyi soyle kurabiliriz.

public void executeDisjunctionCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
Criterion salary = Restrictions.gt("salary",1500);
Criterion name = Restrictions.like("emp_name", "L%");
Criterion surname = Restrictions.ilike("emp_surname", "C%");
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(salary);
disjunction.add(name);
disjunction.add(surname);
crit.add(disjunction);
List results = crit.list();
displayCriteriaList(results);
}

Burada 3 tane Criterion nesnesi olusturduk maasi 1500den buyuk olan kisileri veya adi L ile baslayan kisileri veya soyadi C ile baslayanlari getir dedik.

hibernate_14_output1

Goruldugu gibi maasi 1500 den az olan Levent Erguder de geldi, cunku ismi L ile basliyor, Cagri Cetin de geldi, soy adi C ile basliyor. Sonuc olarak Disjunction dogru calisti.

Bu metodumuzda da SQLRestriction kullanip bir SQL cumlecigi yazabiliriz.

public void executeSQLCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
crit.add(Restrictions.sqlRestriction("emp_name like 'Re%'"));
List results = crit.list();
displayCriteriaList(results);
}

Daha onceki orneklerimizde de Paging ornegi yapmistik.

public void executePagingCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
crit.setFirstResult(1);
crit.setMaxResults(2);
List results = crit.list();
displayCriteriaList(results);
}

setFirstResult(1) ile tablodan cektigimiz ilk kayidi belirtiyoruz ve setMaxResults(2); ile getirebilecegimiz maximum kayit sayisini veriyoruz. (Burada kayit numarasinin dizi mantiginda oldugunu belirtelim, ilk kayidi istiyorsak 0 vermemiz gerekir )

Bu metodumuzda SQL yapimizdan hatirlayacagimiz Order By cumlecigini Criteria API ye uygulamasini yapacagiz.

public void executeOrderCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
crit.add(Restrictions.gt("salary", 1400));
crit.addOrder(Order.desc("salary"));
List results = crit.list();
displayCriteriaList(results);
}

Order.desc ile maasi coktan aza dogru siralayacagiz ( tabi 1400 den az olanlari hesaba katmiyoruz )
Output olarak su degerleri gorebiliriz..

Ozkan Ozbas 2000
Furkan Ilgin 1750
Recep Bostanci 1500

SQL dilinde kullandigimiz Aggregates metotlarini burada da kullanabiliri.

public void executeAggregatesCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.max("salary"));
projList.add(Projections.min("salary"));
projList.add(Projections.avg("salary"));
projList.add(Projections.countDistinct("emp_name"));
crit.setProjection(projList);
List results = crit.list();
displayObjectsList(results);
}

2000 1000 1500.0 5

Outputumuz yukaridaki gibi.. Goruldugu gibi istenilen degerler basariyla dondu !
Burada listeleme yontemi olarak bir baska metot kullandik..

public void displayObjectsList(List list) {
Iterator iter = list.iterator();
if (!iter.hasNext()) {
System.out.println("No objects to display.");
return;
}
while (iter.hasNext()) {
Object[] obj = (Object[]) iter.next();
for (int i = 0; i < obj.length; i++) {
System.out.print(obj[i]+ " ");
}
System.out.println();
}

}

Bu metot yardimi ile Projection ornegi yapalim. Projection , SQL de kayit getirirken diledigimiz alanlari getirmek olarak ifade edilebilir. Yani Select * degil de, Select emp_name.. gibi sorgu yazip istenilen alanlari getirmektir.

public void executeProjectionCriteria(Session session) {
Criteria crit = session.createCriteria(Employee1.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("emp_name"));
projList.add(Projections.property("emp_surname"));
crit.setProjection(projList);
List results = crit.list();
displayObjectsList(results);
}

 

hibernate_14_output2

Goruldugu gibi her kayit(object) icin sadece emp_name ve emp_surname alanini getirdik

CriteriaTest.java

 
package hibernate13_Criteria;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 *
 * @author Levent
 */
public class CriteriaTest {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Employee1.class);
        config.configure("hibernate3.cfg.xml");

        //new SchemaExport(config).create(true, true);

        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        CriteriaTest example = new CriteriaTest();

        String action = "addRecord";
        if (action.equalsIgnoreCase("addRecord")) {
            example.addRecord(session);

        } else {

            Method method = CriteriaTest.class.getMethod(action,
                    new Class[]{Session.class});
            method.invoke(example, new Object[]{session});
        }

        session.getTransaction().commit();

    }

    public void addRecord(Session session) {

        Employee1 emp1 = new Employee1();
        emp1.setEmp_name("Levent");
        emp1.setEmp_surname("Erguder");
        emp1.setSalary(1000);
        session.save(emp1);

        Employee1 emp2 = new Employee1();
        emp2.setEmp_name("Recep");
        emp2.setEmp_surname("Bostanci");
        emp2.setSalary(1500);
        session.save(emp2);

        Employee1 emp3 = new Employee1();
        emp3.setEmp_name("Furkan");
        emp3.setEmp_surname("Ilgin");
        emp3.setSalary(1750);
        session.save(emp3);

        Employee1 emp4 = new Employee1();
        emp4.setEmp_name("Cagri");
        emp4.setEmp_surname("Cetin");
        emp4.setSalary(1250);
        session.save(emp4);

        Employee1 emp5 = new Employee1();
        emp5.setEmp_name("Ozkan");
        emp5.setEmp_surname("Ozbas");
        emp5.setSalary(2000);
        session.save(emp5);

    }

    public void executeSimpleCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        List results = crit.list();
        System.out.println(results.toString());
        displayCriteriaList(results);
    }

    public void executeEqualsCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.eq("emp_name", "Levent"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeNotEqualsCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.ne("emp_name", "Levent"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeLikePatternCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.like("emp_name", "Le%"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeGreaterThanCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.gt("salary", 1400));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeAndCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.gt("salary", 1000));
        crit.add(Restrictions.like("emp_name", "R%"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeOrCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        Criterion salary = Restrictions.gt("salary", 1600);
        Criterion name = Restrictions.like("emp_name", "R%");
        LogicalExpression orExp = Restrictions.or(salary, name);
        crit.add(orExp);
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeDisjunctionCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        Criterion salary = Restrictions.gt("salary", 1500);
        Criterion name = Restrictions.like("emp_name", "L%");
        Criterion surname = Restrictions.ilike("emp_surname", "C%");
        Disjunction disjunction = Restrictions.disjunction();
        disjunction.add(salary);
        disjunction.add(name);
        disjunction.add(surname);
        crit.add(disjunction);
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeSQLCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.sqlRestriction("emp_name like 'Re%'"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executePagingCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.setFirstResult(1);
        crit.setMaxResults(2);
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeOrderCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        crit.add(Restrictions.gt("salary", 1400));
        crit.addOrder(Order.desc("salary"));
        List results = crit.list();
        displayCriteriaList(results);
    }

    public void executeAggregatesCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        ProjectionList projList = Projections.projectionList();
        projList.add(Projections.max("salary"));
        projList.add(Projections.min("salary"));
        projList.add(Projections.avg("salary"));
        projList.add(Projections.countDistinct("emp_name"));
        crit.setProjection(projList);
        List results = crit.list();
        displayObjectsList(results);
    }

    public void executeProjectionCriteria(Session session) {
        Criteria crit = session.createCriteria(Employee1.class);
        ProjectionList projList = Projections.projectionList();
        projList.add(Projections.property("emp_name"));
        projList.add(Projections.property("emp_surname"));
        crit.setProjection(projList);
        List results = crit.list();
        displayObjectsList(results);
    }

    public void displayCriteriaList(List list) {
        Iterator iter = list.iterator();
        if (!iter.hasNext()) {
            System.out.println("No Results..");
            return;
        }
        while (iter.hasNext()) {
            Employee1 employee1 = (Employee1) iter.next();
            String msg = employee1.getEmp_name() + " " + employee1.getEmp_surname() + "\t" + employee1.getSalary();
            System.out.println(msg);
        }
    }

    public void displayObjectsList(List list) {
        Iterator iter = list.iterator();
        if (!iter.hasNext()) {
            System.out.println("No objects to display.");
            return;
        }
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            for (int i = 0; i < obj.length; i++) {
                System.out.print(obj[i] + " ");
            }
            System.out.println();

        }
    }
}

Bu yazimizi da burada sonlandiriyoruz .

Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
injavawetrust

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published.