HIBERNATE - INTERCEPTORS

Similar documents
HIBERNATE - MANY-TO-ONE MAPPINGS

HIBERNATE - COMPONENT MAPPINGS

HIBERNATE - SORTEDSET MAPPINGS

HIBERNATE - ONE-TO-ONE MAPPINGS

Installing MySQL. Hibernate: Setup, Use, and Mapping file. Setup Hibernate in IDE. Starting WAMP server. phpmyadmin web console

Unit 6 Hibernate. List the advantages of hibernate over JDBC

TPCT s College of Engineering, Osmanabad. Laboratory Manual ADVANCED JAVA. For. Third Year Students. Manual Prepared by. Mr.A.A.

G l a r i m y TeachCode Series. Hibernate. Illustrated. Krishna Mohan Koyya

Step By Step Guideline for Building & Running HelloWorld Hibernate Application

Chapter 2. Introduction to Mapping

Chapter 3. Harnessing Hibernate

Database Application Architectures

International Journal of Advance Research in Engineering, Science & Technology HIBERNATE FRAMEWORK FOR ENTERPRISE APPLICATION

IBATIS - QUICK GUIDE IBATIS - OVERVIEW

Study of Hibernate. Akash Ravindra. Khapare

INTERFACE WHY INTERFACE

Integration Of Struts2 And Hibernate Frameworks

MYBATIS - ANNOTATIONS

Tutorial Hibernate Annotaion Simple Book Library

Introduction to Classes and Objects

The Object-Oriented Paradigm. Employee Application Object. The Reality of DBMS. Employee Database Table. From Database to Application.

Lessons learned so far... Wednesday, January 26, :16 PM

Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics:

First Name: AITI 2004: Make-up Exam 1 July 9, Last Name:

1 st Step. Prepare the class to be persistent:

TP 6 des architectures logicielles Séance 6 : Architecture n-tiers avec du JPA avec plusieurs entités. 1 Préparation de l environnement Eclipse

Transaction Management Chapter 11. Class 9: Transaction Management 1

Introduction to Classes and Objects

Chapter 4. Collections and Associations

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

SPRING DECLARATIVE TRANSACTION MANAGEMENT

JPA Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

Banaras Hindu University

Introduction to Session beans. EJB - continued

WEEK 13 EXAMPLES: POLYMORPHISM

PASS4TEST IT 인증시험덤프전문사이트

Programming II (CS300)

PART 1. Eclipse IDE Tutorial. 1. What is Eclipse? Eclipse Java IDE

Answer ALL Questions. Each Question carries ONE Mark.

JPA - ENTITY MANAGERS

Lab05: Inheritance and polymorphism

Module 8 The Java Persistence API

IST311 Chapter 8: C# Collections - Index-Sequential Search List & Dictionary PROGRAM

Warm-up: Revisiting selected data technologies via 101companies

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Exploring EJB3 With JBoss Application Server Part 6.2

Java and XML. XML documents consist of Elements. Each element will contains other elements and will have Attributes. For example:

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Object-Oriented Programming in Java. Topic : Objects and Classes (cont) Object Oriented Design

Exploring EJB3 With JBoss Application Server Part 6.3

Lightweight J2EE Framework

Introduction to Programming

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Java Object/Relational Persistence with Hibernate. David Lucek 11 Jan 2005

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Full file at

Java Foundations Certified Junior Associate


An application to create problem-specific document object models for XML

Inheritance Introduction. 9.1 Introduction 361

SSE3052: Embedded Systems Practice

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Java Database Connectivity (JDBC) 25.1 What is JDBC?

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Name:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Xcalia Intermediation Core Mapping Quick Reference

How to define your own classes that implement abstractions. How to pass information to methods and how methods return values.

Full file at Chapter 2 - Inheritance and Exception Handling

Lab Assignment 13 (week 13)

CLASS DESIGN. Objectives MODULE 4

Table of Contents - Fast Track to Hibernate 3

Introduction to Programming Using Java (98-388)

Accelerating Information Technology Innovation

Using Java reflection to reduce Code and Development time in DFS

Handling XML data with Java

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Create a Java project named week9

public static boolean isoutside(int min, int max, int value)

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses

d. If a is false and b is false then the output is "ELSE" Answer?

Chapter 2 How to structure a web application with the MVC pattern

ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Fundamentals of Programming Data Types & Methods

So, this tutorial is divided into various chapters for the simple presentation and easy understanding.

sqoop Automatic database import Aaron Kimball Cloudera Inc. June 18, 2009

PROGRAMMING FUNDAMENTALS

Model Driven Architecture with Java

Programming II (CS300)

Entity LifeCycle Callback Methods Srikanth Technologies Page : 1

ADF Mobile Code Corner

Ch 7 Designing Java Classes & Class structure. Methods: constructors, getters, setters, other e.g. getfirstname(), setfirstname(), equals()

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

ADF Mobile Code Corner

Using DBMaker with J2EE Application Server Manual Version: 01.01

Communication Software Exam 5º Ingeniero de Telecomunicación January 26th Name:

Thu 10/26/2017. Created RESTful Web Service, JavaDB, Java Persistence API, Glassfish server in NetBeans 8

Transcription:

HIBERNATE - INTERCEPTORS http://www.tutorialspoint.com/hibernate/hibernate_interceptors.htm Copyright tutorialspoint.com As you have learnt that in Hibernate, an object will be created and persisted. Once the object has been changed, it must be saved back to the database. This process continues until the next time the object is needed, and it will be loaded from the persistent store. Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks. These methods are callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. Following is the list of all the methods available within the Interceptor interface: S.N. Method and Description 1 finddirty This method is be called when the flush method is called on a Session object. 2 instantiate This method is called when a persisted class is instantiated. 3 isunsaved This method is called when an object is passed to the saveorupdate method/ 4 ondelete This method is called before an object is deleted. 5 onflushdirty This method is called when Hibernate detects that an object is dirty ie. havebeenchanged during a flush i.e. update operation. 6 onload This method is called before an object is initialized. 7 onsave This method is called before an object is saved. 8 This method is called after a flush has occurred and an object has been updated in memory. 9 This method is called before a flush. Hibernate Interceptor gives us total control over how an object will look to both the application and the database.

How to use Interceptors? To build an interceptor you can either implement Interceptor class directly or extend EmptyInterceptor class. Following will be the simple steps to use Hibernate Interceptor functionality. Create Interceptors: We will extend EmptyInterceptor in our example where Interceptor's method will be called automatically when Employee object is created and updated. You can implement more methods as per your requirements. import java.io.serializable; import java.util.date; import java.util.iterator; import org.hibernate.emptyinterceptor; import org.hibernate.transaction; import org.hibernate.type.type; public class MyInterceptor extends EmptyInterceptor { private int updates; private int creates; private int loads; public void ondelete(object entity, Object[] state, // do nothing // This method is called when Employee object gets updated. public boolean onflushdirty(object entity, Object[] currentstate, Object[] previousstate, if ( entity instanceof Employee ) { System.out.println("Update Operation"); return true; return false; public boolean onload(object entity, Object[] state, // do nothing return true; // This method is called when Employee object gets created. public boolean onsave(object entity, Object[] state, if ( entity instanceof Employee ) { System.out.println("Create Operation"); return true; return false; //called before commit into database

public void (Iterator iterator) { System.out.println(""); //called after committed into database public void (Iterator iterator) { System.out.println(""); Create POJO Classes: Now let us modify a little bit our first example where we used EMPLOYEE table and Employee class to play with: public class Employee { private int id; private String firstname; private String lastname; private int salary; public Employee() { public Employee(String fname, String lname, int salary) { this.firstname = fname; this.lastname = lname; this.salary = salary; public int getid() { return id; public void setid( int id ) { this.id = id; public String getfirstname() { return firstname; public void setfirstname( String first_name ) { this.firstname = first_name; public String getlastname() { return lastname; public void setlastname( String last_name ) { this.lastname = last_name; public int getsalary() { return salary; public void setsalary( int salary ) { this.salary = salary; Create Database Tables: Second step would be creating tables in your database. There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table: create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Create Mapping Configuration File:

This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="employee" table="employee"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator /> </id> <property name="firstname" column="first_name" type="string"/> <property name="lastname" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> Create Application Class: Finally, we will create our application class with the main method to run the application. Here it should be noted that while creating session object we used our Interceptor class as an argument. import java.util.list; import java.util.date; import java.util.iterator; import org.hibernate.hibernateexception; import org.hibernate.session; import org.hibernate.transaction; import org.hibernate.sessionfactory; import org.hibernate.cfg.configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(string[] args) { factory = new Configuration().configure().buildSessionFactory(); catch (Throwable ex) { System.err.println("Failed to create sessionfactory object." + ex); throw new ExceptionInInitializerError(ex); ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empid1 = ME.addEmployee("Zara", "Ali", 1000); Integer empid2 = ME.addEmployee("Daisy", "Das", 5000); Integer empid3 = ME.addEmployee("John", "Paul", 10000); /* List down all the employees */ ME.listEmployees(); /* Update employee's records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down new list of the employees */ ME.listEmployees(); /* Method to CREATE an employee in the database */

public Integer addemployee(string fname, String lname, int salary){ Integer employeeid = null; Employee employee = new Employee(fname, lname, salary); employeeid = (Integer) session.save(employee); catch (HibernateException e) { finally { return employeeid; /* Method to READ all the employees */ public void listemployees( ){ List employees = session.createquery("from Employee").list(); for (Iterator iterator = employees.iterator(); iterator.hasnext();){ Employee employee = (Employee) iterator.next(); System.out.print("First Name: " + employee.getfirstname()); System.out.print(" Last Name: " + employee.getlastname()); System.out.println(" Salary: " + employee.getsalary()); catch (HibernateException e) { finally { /* Method to UPDATE salary for an employee */ public void updateemployee(integer EmployeeID, int salary ){ Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setsalary( salary ); session.update(employee); catch (HibernateException e) { finally { /* Method to DELETE an employee from the records */ public void deleteemployee(integer EmployeeID){ Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); catch (HibernateException e) {

finally { Compilation and Execution: Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. Create hibernate.cfg.xml configuration file as explained in configuration chapter. Create Employee.hbm.xml mapping file as shown above. Create Employee.java source file as shown above and compile it. Create MyInterceptor.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Execute ManageEmployee binary to run the program. You would get following result, and records would be created in EMPLOYEE table. $java ManageEmployee...VARIOUS LOG MESSAGES WILL DISPLAY HERE... Create Operation Create Operation Create Operation First Name: Zara Last Name: Ali Salary: 1000 First Name: Daisy Last Name: Das Salary: 5000 First Name: John Last Name: Paul Salary: 10000 Update Operation First Name: Zara Last Name: Ali Salary: 5000 First Name: John Last Name: Paul Salary: 10000 If you check your EMPLOYEE table, it should have following records: mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ id first_name last_name salary +----+------------+-----------+--------+ 29 Zara Ali 5000 31 John Paul 10000 +----+------------+-----------+--------+ 2 rows in set (0.00 sec mysql> Processing math: 100%