Posts

Hibernate Interceptor Lesson

We will use following files Entity.java Entity.hbm.xml hibernate.cfg.xml MyInterceptor.java HibernateEngine.java Entity.java public class Entity{ private int id; String name; String category; } Entity.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="javafiles.Entity" table="ENTITIES_DATA"> <id name="id" column="ID" > <generator class="assigned" /> </id> <property name="name" column="NAME" length="20"/> <property name="category" column="CATEGORY" length="20"/> </class> </hibernate-mapping> MyInterceptor.java package javafiles; import java.io.Serializable; import java.util.Iterator; import org.hibernate.CallbackE...

Hibernate Interceptor

Interceptor Interface provides methods which can be called at different stages to perform some required tasks. Interceptor 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. Hibernate Interceptor gives us total control over how an object will look to both the application and the database. To build/use an interceptor we can either implement Interceptor interface directly or extend EmptyInterceptor class . Following are some of the methods available within the Interceptor interface: Method and Description findDirty() This method is be called when the flush() method is called on a Session object. instantiate() This method is called when a persisted class is instantiated. isUnsaved() This method is called when an object is passed to the saveOrUpdate() method onDelete() This method is called before an object is deleted. When object is not...

Hibernate Batch Processing Insert Operation

We will use following files Student.java Student.hbm.xml hibernate.cfg.xml HibernateEngine.java Student.java public class Student { private int rollNumber; private String name; private String address; // set and get method } Student.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="javafiles.Student" table="STUDENTS_DATA"> <id name="rollNumber" column="ROLL_NUMBER" > <generator class="assigned" /> </id> <property name="name" column="NAME" length="20"/> <property name="address" /> </class> </hibernate-mapping> Hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-config...

Batch Processing

Friends, batch processing means processing insert ,udate and delete operations in batch or bulk, Just for the sake of our understanding lets take a small example, If we want to insert 100000 records into the database then our code will be as below Session sessionObj = sessionFactoryObj.openSession(); Transaction transactionObj = sessionObj.beginTransaction(); for ( int y=0; y<100000; y++ ) { House houseObj = new House(……); session.save(houseObj); } transactionObj.commit(); sessionObj.close(); Friends what do you think , will it run successfully ?? No ! This will fail with an OutOfMemoryException somewhere around the 50,000th row. That is because Hibernate caches all the newly inserted Customer instances in the session-level cache. To overcome this problem If you are undertaking batch processing you will need to enable the use of JDBC batching. This is absolutely essential if you want to achieve optimal performance. Set the JDBC batch size to a appropriate number ...

Hibernate One to One Update operation

// For pojo see the One to One Insert operation import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngine { public static void main(String[] javaPlanet) { System.out.println(" ....... ENGINE START ............"); System.out.println(" ....... ONE TO ONE ANNOTATION UPDATE LESSON ............\n"); Configuration configurationObj = new Configuration(); configurationObj.configure("hibernate.cfg.xml"); SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory(); Session sessionObj = sessionFactoryObj.openSession(); Result resultObj = (Result) sessionObj.get(Result.class, new Integer(4)); Pupil pupilObj= resultObj.getPupil(); pupilObj.setName("Mansukh"); Transaction transaction=sessionObj.beginTransaction(); sessionObj.update(resultObj); transaction.commit(); System.out.println("\n....... DATA UPDATED SUCCESSFULLY ....

Hibernate One To One Insert Operation

We will use following files Pupil.java Result.java hibernate.cfg.xml HibernateEngineInsert.java Pupil.java @Entity @Table(name="PUPILS_DATA") public class Pupil{ @Id @Column(name="ROLL_NUMBER") int rollNumber; @Column(name="NAME") String name; @Column(name="ADDRESS") String address; @OneToOne(targetEntity=Result.class,cascade=CascadeType.ALL) @JoinColumn(name="ROLL_NUMBER",referencedColumnName="ROLL_NUMBER") Result result; // set and get methods } Result.java @Entity @Table(name="PUPILS_RESULTS_DATA") public class Result { @Id @Column(name="ROLL_NUMBER") private int rollNumber; @Column(name="MATHS_MARKS") private int mathsMarks; @Column(name="SCIENCE_MARKS") private int scienceMarks; @Column(name="TOTAL_MARKS") private int totalMarks; @OneToOne(targetEntity=Pupil.class,cascade=CascadeType.ALL) @JoinColumn(name="ROLL_NUMBER",referencedColumnNa...

Hibernate Many to Many Update Operation

// For SQL and POJO see the Many to Many Insert Operation import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngine { public static void main(String[] javaPlanet) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. MANY TO MANY ANNOTATION UPDATE LESSON ..\n"); Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); User userObj = (User) session.get(User.class, new Integer(2)); userObj.setName("Dharm"); Set<MobilePhone> mobilePhoneSet = userObj.getMobilePhones(); for(MobilePhone phone:mobilePhoneSet){ if(phone.getModelNumber()==11)     phone.setName("SAMSUNG galaxy NOTE"); } userObj.setMobilePhones(mobilePhoneSet); Transaction...

Hibernate Many To Many Insert Operation

We will use following files User.java MobilePhone.java HibernateEngine.java hibernate.cfg.xml Queries CREATE TABLE MOBILE_PHONES_DATA ( PHONE_ID INT PRIMARY KEY AUTO_INCREMENT, MODEL_NUMBER INT, MODEL_NAME VARCHAR(20)); CREATE TABLE USERS_DATA ( USER_ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), ADDRESS VARCHAR(35)); CREATE TABLE MOBILE_PHONES_AND_USERS_REL( MOBILE_PHONE_ID INT, MOBILE_USER_ID INT, FOREIGN KEY (MOBILE_PHONE_ID) REFERENCES MOBILE_PHONES_DATA (PHONE_ID), FOREIGN KEY (MOBILE_USER_ID) REFERENCES USERS_DATA (USER_ID)); User.java @Entity @Table(name="USERS_DATA") public class User { @Id @GeneratedValue @Column(name="USER_ID") private int id; @Column(name="NAME") private String name; @Column(name="ADDRESS") private String address; //@ManyToMany(targetEntity=MobilePhone.class,mappedBy="users") @ManyToMany(targetEntity=MobilePhone.class, cascade=CascadeType.ALL) @JoinTable(name=...

Hibernate Many to One delete Operation

// For SQL and POJO see the Many to One Insert Operation : Here import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngine { public static void main(String[] javaPlanet) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. MANY TO ONE ANNOTATION DELETE LESSON ..\n"); Configuration condigurationObj = new Configuration(); condigurationObj.configure("hibernate.cfg.xml"); SessionFactory factoryObj = condigurationObj.buildSessionFactory(); Session sessionObj = factoryObj.openSession(); Children childObj= (Children) sessionObj.get(Children.class, new Integer(3)); Transaction transaction=sessionObj.beginTransaction(); sessionObj.delete(childObj); transaction.commit(); System.out.println("\n....... DATA DELETED SUCCESSFULLY .........."); sessionObj.close(); factoryObj.close(); System.out.println("\n......

Hibernate Many to One Update Operation

// For SQL and POJO see the Many to One Insert Operation : Here import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngine { public static void main(String[] javaWorld) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. MANY TO ONE ANNOTATION UPDATE LESSON .."); Configuration condigurationObj = new Configuration(); condigurationObj.configure("hibernate.cfg.xml"); SessionFactory factoryObj = condigurationObj. buildSessionFactory (); Session sessionObj = factoryObj.openSession(); Children childObj = (Children) sessionObj.get(Children.class, new Integer(1)); childObj.setName("Nandni"); childObj.setAge(20); /* In below two line we are changing the already exist parent name*/ Parent parentObj = childObj.getParentObj(); parentObj.setName("Divya"); /* Using below three line ...

Hibernate Many To One Insert Operation

We will use following files Parent.java Children.java hibernate.cfg.xml HibernateEngine.java Queries CREATE TABLE PARENTS_DATA (PARENT_ID INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20)); CREATE TABLE CHILDREN_DATA (CHILD_ID INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),AGE INT,PARENT_ID INT); Parent.java @Entity @Table(name="PARENTS_DATA") public class Parent { @Id @GeneratedValue(strategy=IDENTITY) @Column(name="PARENT_ID") private int id=0; @Column(name="NAME") private String name; @OneToMany(fetch=FetchType.LAZY, targetEntity=Children.class, cascade=CascadeType.ALL) @JoinColumn(name="PARENT_ID",referencedColumnName="PARENT_ID") private Set children; // provide set and get methods for all members }  Children.java @Entity @Table(name="CHILDREN_DATA") public class Children { @Id @GeneratedValue @Column(name="CHILD_ID") private int id; @Column(name="NAME") private String name; ...

Hibernate One to Many delete Operation

// FOR TABLE and  POJO  see the One to Many Insert Operation : Here import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngineDelete { public static void main(String[] javaPlanet) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. ONE TO MANY ANNOTATION DELETE LESSON ..\n"); Configuration configurationObj = new Configuration(); configurationObj.configure("hibernate.cfg.xml"); SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory(); Session sessionObj = sessionFactoryObj.openSession(); Parent parentObj= (Parent) sessionObj.get(Parent.class, new Integer(101)); Transaction transaction=sessionObj.beginTransaction(); sessionObj.delete(parentObj); transaction.commit(); System.out.println("\n....... DATA DELETED SUCCESSFULLY .........."); sessionObj.close(); sessionFactoryObj.close(); S...

Hibernate One to Many update Operation

// FOR TABLE and  POJO  see the One to Many Insert Operation : Here import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngine_Update { public static void main(String[] javaWorld) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. ONE TO MANY ANNOTATION UPDATE LESSON .."); Configuration configurationObj = new Configuration(); configurationObj.configure("hibernate.cfg.xml"); SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory(); Session sessionObj = sessionFactoryObj.openSession(); Parent parentObj= (Parent) sessionObj.get(Parent.class, new Integer(101)); parentObj.setName("Sunny"); Set<Children> childrenSet=parentObj.getChildren(); for(Children child:childrenSet){ child.setName("parker"); child.setAge(20); } parentObj.setChildren(children...

Hibernate One to Many Select Operation

// FOR TABLE and  POJO  see the One to Many Insert Operation : Here import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateEngineSelect { public static void main(String[] javaWorld) { System.out.println(" ....... ENGINE START ............"); System.out.println(" .. ONE TO MANY ANNOTATION SELECT LESSON ..\n"); Configuration config = new Configuration(); config .configure("hibernate.cfg.xml"); SessionFactory sessFact = config .buildSessionFactory(); Session sessionObj = sessFact .openSession(); Parent parentObj= (Parent) sessionObj.get(Parent.class, new Integer(101)); System.out.println("\n----------Parent Data----------"); System.out.println("Parent Id :"+parentObj.getId()); System.out.println("Parent Name : "+parentObj.getName()); System.out.println("---------------(:-)---------------\n...

Hibernate One to Many Relationship

According to database terminology, one row of one table related with multiple rows of other table. According to hibernate, one object of one POJO class related to multiple objects of other POJO class I mean, one [Parent] to many [Children], one [Teacher] to many [Student], example of oneto- many is some thing category books contains different type of books, one vendor contains lot of customers etc. To achieve one-to-many between two POJO classes in the hibernate, then the following two changes are required. In the parent POJO class, we need to take a collection property, the collection can be eitherSet,List,Map. In the mapping file of that parent POJO class, we need to configure the collection. We will use following files : Parent.java [POJO class] Parent.hbm.xml Children.java [POJO class] Children.hbm.xml hibernate.cfg.xml HibernateEngine.java Queries   CREATE TABLE PARENTS_DATA (PARENT_ID INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20)) CREATE TABLE CHILDREN_D...

Hibernate Named Query

1) While executing either HQL, NativeSQL Queries if we want to execute the same queries for multiple times and in more than one client program application then we can use the NamedQueries mechanism. 2) In this Named Queries concept, we use some name for the query configuration, and that name will be used when ever the same query is required to execute. 3) In hibernate mapping file we need to configure a query by putting some name for it and in the client application, we need to use getNamedQuery() given by session interface, for getting the Query reference and we need to execute that query by calling list(). 4) If you want to create Named Query then we need to use query element in the hibernate mapping file Syntax Of hibernate mapping file <hibernate-mapping> <class name="---" table="---"> <id name="---" column="---" /> <property name="---" column="---" length="10"/> <proper...

Native SQL Example

Configuration configurationObj = new Configuration(); configurationObj.configure("hibernate.cfg.xml"); SessionFactory sessionFactoryObj = configurationObj.buildSessionFactory(); Session sessionObj = sessionFactoryObj.openSession(); System.out.println("\n---------USING OBJECT ARRAY--------\n"); SQLQuery sqlQuery1 = sessionObj.createSQLQuery(" SELECT * FROM ITEMS_DATA"); List itemList1 = sqlQuery1.list(); Iterator itemListIterator1 = itemList1.iterator(); System.out.println("ID \t NAME \t CATEGORY "); System.out.println("--------------------------"); while(itemListIterator1.hasNext()){       Object data[]=(Object[])itemListIterator1.next();       System.out.print(data[0]+"\t");       System.out.print(data[1]+"\t");       System.out.println(data[2]); } System.out.println("--------------------------"); System.out.println("\n---------USING POJO CLASS------------\n"); SQLQuery sq...

How to use Native SQL?

SQLQuery query = session.createSQLQuery(" select * from ENTITIES_DATA "); // Here ENTITIES_DATA is the table in the database List list = query.list(); Iterator iterator = list.iterator(); while(iterator.hasNext()) {   Object row[] = (Object[])iterator.next();   /*----- further code--------*/ } while selecting data from the table, even though you are selecting the complete object from the table, in while loop still we type cast into object array only right See the above code, we typecast into the object[] arrays, in case if we want to type cast into our POJO class (i mean to get POJO class obj), then we need to go with entityQuery concept In order to inform the hibernate that convert each row of ResultSet into an object of the POJO  class back, we need to make the query as an entityQuery To make the query as an entityQuery, we need to call addEntity() method How to use addEntity() ? //We are letting hibernate to know our POJO class too SQLQuery qr...

Native SQL Query

Hibernate Native SQL Query Native SQL is another technique of performing bulk operations on the data using hibernate By using Native SQL, we can perform both select, non-select operations on the data Native SQL means using the direct SQL command specific to the particular (current using) database and executing it with using hibernate Advantages and Disadvantages of Native SQL We can use the database specific keywords (commands), to get the data from the database. While migrating a JDBC program into hibernate, the task becomes very simple because JDBC uses direct SQL commands and hibernate also supports the same commands by using this Native SQL The main draw back of Native SQL is, some times it makes the hibernate application as database dependent one Native SQL If we want to execute Native SQL Queries on the database then, we need to construct an object of SQLQuery, actually this SQLQuery is an interface extended from Query and it is given in ” org.hibernate packag...

Difference between HQL and Criteria Query

HQL is to perform both select and non-select operations on the data, but Criteria is only  for selecting the data, we cannot perform non-select operations using criteria HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries HQL doesn’t support pagination concept, but we can achieve pagination with Criteria Criteria used to take more time to execute then HQL With Criteria we are safe with SQL Injection because of its dynamic query generation but  in HQL as your queries are either fixed or parameterized, there is no safe from SQL Injection.