Hibernate Ders 15 – Filter

Merhaba Arkadaslar,
Bu dersimizde Hibernate’te Filter konusunu isleyecegiz ve ornek bir uygulama yapacagiz.

Hibernate “filter” ile istenmeyen datayi elimine edebiliriz.Filtreleme islemeni SQL ile yapabiliriz, (where araciligi ile ) veya Hibernate Criteria Api ile fakat Hibernate daha merkezi bir sistem ile bu durumun üstesinden geliyor.

Bir uygulamasi dusunelim ve hava alani için cesitli uçuş raporlaru veriyor.Ucuslarin (on time, delayed ve cancelled gibi durumlari olduğunu düşünelim ) ve durumlarin degistigini goz onunde bulundurursak , bu durum where ile çözülebilir, kucuk uygulamalar için bu durum problem yaratmazken buyuk ve karisik uygulamalar için problem yaratabilir.

Bu ornegimizde diger orneklerimizin disinda PostgreSQL degil MYSQL kullanacagiz bunu yapabiliriz oyle degil mi ? Nasil olsa Hibernate bize bu ozgurlugu sagliyor.

Yeni bir schema olusturdum, hibernate_filter_demo ismini verdim semamiza.

Mysql query browserimizi acip, su kodlari calistiralim.. (not sagda hibernate_filter_demo semasini secmeyi unutmayalim)

CREATE TABLE FLIGHT_DB(
ID INTEGER NOT NULL,
FLIGHT_NO VARCHAR(10)NOT NULL,
SOURCE VARCHAR(15) NOT NULL,
DESTINATION VARCHAR(15) NOT NULL,
STATUS VARCHAR(20) NOT NULL,
PRIMARY KEY (ID)
);

Mysql veritabani yonetim sistemimizde, hibernate_filter_demo semamizda FLIGHT_DB isimli tablomuzu olusturduk simdi tekrar Netbeans IDE mize donuyoruz…

Projemizde default package kismina sag tiklayalim..
New —> Other –> Hibernate —–> Hibernate Configuration Wizard diyoruz..

hibernate_configuration_wizard

 

next–> burada isim veriyoruz hibernate4.cfg , dokunmadan devam ediyorum.. next —>  karsimiza data source ekrani gelecek.. New Database Connection diyoruz.

newdataconnection

Driver i sececegiz… MYSQL connector u seciyoruz..

newconnectionwizard

 

Host —> localhost
port —->3306
Database—->hibernate_filter_demo
username—>root [ degistirdiyseniz neyse o 🙂 ]
password—> ben de yok.
Test connetion diyelim ve sol atta Connection Succeeded i gordugumuzu varsayiyorum 🙂

hibernate_new_connection

Default package imiza sag tikliyoruz.. New—->Other—>Hibernate—> Hibernate Reverse Engineering Wizard diyoruz, next—> next–>
Configuration file comboboxinda biraz once olusturdugumuz hibernate4.cfg.xml i seciyoruz.

new_hibernate_reverse_eng
Avaiable tables alaninda , biraz once olusturdugumuz flight_db tablomuz var. Tablomuzu secip add diyoruz ve finish ile olayi bitiriyoruz..

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="hibernate_filter_demo"/>
<table-filter match-name="flight_db"/>
</hibernate-reverse-engineering>

Source Package imiza sag tiklayalim…New–>Other—>Hibernate—> Hibernate Mapping Files and POJOS from Database i secip next diyoruz.

Hibernate configuration file olarak hibernate.cfg.xml i seciyoruz. Package ismine hibernate_15_filter yazalim ve Finish i tiklayalim.

hibernate_mapping_files_and_pojos

hibernate15_filter package imiz altinda Flight.java ve Flight.hbm.xml dosyamiz olustu.

Flight.java

package hibernate15_filter;
// Generated Dec 25, 2012 8:41:09 PM by Hibernate Tools 3.2.1.GA

/**
 * FlightDb generated by hbm2java
 */
public class FlightDb  implements java.io.Serializable {

     private int id;
     private String flightNo;
     private String source;
     private String destination;
     private String status;

    public FlightDb() {
    }

    public FlightDb(int id, String flightNo, String source, String destination, String status) {
       this.id = id;
       this.flightNo = flightNo;
       this.source = source;
       this.destination = destination;
       this.status = status;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getFlightNo() {
        return this.flightNo;
    }

    public void setFlightNo(String flightNo) {
        this.flightNo = flightNo;
    }
    public String getSource() {
        return this.source;
    }

    public void setSource(String source) {
        this.source = source;
    }
    public String getDestination() {
        return this.destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }
    public String getStatus() {
        return this.status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

Bu ornegimizde HibernateUtil.java yi kullanacagiz, Netbeans bize bu sinifi olusturmamizi sagliyor. hibernate15_filter package imiz altinda yeni bir package olusturalim adina util dedim, sonra da package imiza sag tiklayip new—> other—> hibernate—-> HibernateUtil.java yi secelim.
Gerekli duzenlemeleri resimdeki sekilde yapalim.

hibernateutil

HibernateUtil.java 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate15_filter.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author Levent
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 

sessionFactory = new AnnotationConfiguration().configure("hibernate4.cfg.xml").buildSessionFactory(); 


HibernateFilterDemo.java

package hibernate15_filter;

import hibernate15_filter.util.HibernateUtil;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Query;
import org.hibernate.Filter;

/**
 * Hibernate Filter Demo
 * 
 * @author ashutosh_sharma03
 * 
 */
public class HibernateFilterDemo
{
	public static void main(String argsp[])
	{
		//First obtain the sessionFactory handle and then open the session
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.openSession();

		//create the data ready for application

		insertData("DL6149", "RIC", "JFK", "ontime",session);
		insertData("CO1948", "EWR", "PHX", "delayed",session);
		insertData("AI0101","JFK","DEL","delayed",session);
		insertData("US1987","LAX","SFO","ontime",session);
		insertData("NW3482","JFK","ATL","cancelled",session);
		insertData("9W5432","JFK","BOM","ontime",session);
		insertData("AI0102","JFK","DEL","ontime",session);

		// you can comment out insert statements above once the data has been setup.

		//show the entire data
//		System.out.println("Showing all the flights");
//		showData(session);

//		//First enable the filter on the session
//		Filter filter = session.enableFilter("statusFilter");
//		
//		// show delayed flights		
//		filter.setParameter("statusParam", "delayed");
////		System.out.println("Showing all the delayed flights");
////		showData(session);
//		
//		//show flights ontime
//		filter.setParameter("statusParam", "ontime");
//		//System.out.println("Showing all the flights ontime");
//		//showData(session);
//		
//		//show cancelled flights.
//		//System.out.println("Showing all the cancelled flights");
//		filter.setParameter("statusParam", "cancelled");
		//showData(session);

		//disabling the filter will show all the flights once again
		session.disableFilter("statusFilter");
		showData(session);

		//finally close the session as we are done
		session.close();
	}

	public static void insertData(String flightNo, String source,
			String destination, String status, Session session)
	{
		session.beginTransaction();

		FlightDb flight = new FlightDb();
		flight.setFlightNo(flightNo);
		flight.setSource(source);
		flight.setDestination(destination);
		flight.setStatus(status);

		session.save(flight);
		session.getTransaction().commit();
	}

	public static void showData(Session session)
	{
		session.beginTransaction();
		Query query = session.createQuery("from FlightDb");
		System.out.println("Flight"+"\tSource"+"\tDestn"+"\tStatus");
		Iterator  iter = query.iterate();
		while (iter.hasNext())
		{
			FlightDb flight = (FlightDb) iter.next();			
			System.out.print(flight.getFlightNo() + "\t"
					+ flight.getSource() + "\t" + flight.getDestination());
			if (flight.getStatus().equalsIgnoreCase("ontime"))
			{
				System.out.print("\t" + flight.getStatus());
			}
			if (flight.getStatus().equalsIgnoreCase("delayed"))
			{
				System.out.print("\t" + flight.getStatus());
			}
			if (flight.getStatus().equalsIgnoreCase("cancelled"))
			{
				System.out.print("\t" + flight.getStatus());
			}
			System.out.println();
		}
		session.getTransaction().commit();
	}
}

FlightDb.hbm.xml e eklenti yapiyoruz filter ismini ve parametresini ayarliyoruz..

<filter name="statusFilter" condition=":statusParam=status"/>
<filter-def name="statusFilter">
<filter-param name="statusParam" type="string"/>
</filter-def>

< generator class = ” assigned ” /> olan kismi degistiriyoruz, burada idi kendimiz atamayacagiz otomatik olarak verecegimiz icin “increment” yapacagiz..

Ve artik haziriz…
HibernateFilterDemo.java sinifimiza gelelim ve calistiralim.

insertData(“DL6149”, “RIC”, “JFK”, “ontime”,session);
insertData(“CO1948”, “EWR”, “PHX”, “delayed”,session);
insertData(“AI0101″,”JFK”,”DEL”,”delayed”,session);
insertData(“US1987″,”LAX”,”SFO”,”ontime”,session);
insertData(“NW3482″,”JFK”,”ATL”,”cancelled”,session);
insertData(“9W5432″,”JFK”,”BOM”,”ontime”,session);
insertData(“AI0102″,”JFK”,”DEL”,”ontime”,session);

komutlari ile kayitlarimizi ekledik

hibernateinsertdate

kayitlarimiz basariyla eklendi , insertData kisimlari yorum satiri haline getirelim,tekrar kayit eklememek icin.

session.disableFilter("statusFilter");
showData(session);

Ilk basta default olarak filtre eklemedik, filtreyi disable yaptik ! Bu kismi yorum satiri haline getirelim.

filter.setParameter("statusParam", "delayed");
System.out.println("Showing all the delayed flights");
showData(session); 

Kismini aktif hale getirsek delayed durumdaki ucuslarin listesini gorebiliriz.

delayed

filter.setParameter("statusParam", "ontime");
System.out.println("Showing all the flights ontime");
showData(session);

Kismini da aktif  edersek hem delayed durumundaki hem ontime durumundaki ucuslarin listesini gorebiliriz..

Peki bu durumu nasil sagliyoruz…. ?????
FlightDb.hbm.xml icerisinde ekledigimiz

<filter name="statusFilter" condition=":statusParam=status"/>
araciligiyla sagliyoruz..
Filter filter = session.enableFilter("statusFilter");

kisminda filtremizin ismini veriyoruz.
condition kismindaki statusParam ismiyle
filter.setParameter(“statusParam”, “delayed”);  kismindaki statusParamin ayni olduguna dikkat edelim.tablodaki status alani araciligiyla , gonderdigimiz degere gore (ontime,delayed gibi…) sorgularin sonuclarini bize getiriyor. ( ayni islem where ile de yapilabilir niye bu kadar ugrastik 🙂 yazimizin basinda nedeninden bahsetmistik )

Kaynak Kodlar: HibernateTutorial_v15
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.