Hibernate

Introduction

In most of the applications, after creating the data, you want to save them to, probably, a Relational Database. The process of creating this data was about dealing with methods, Classes and Objects, while the step of saving it to the Database, is about dealing with tables, relations, columns and records. This switch between the two paradigms is tiring and time consuming.

Hibernate simplifies this process by simply mapping your Relational Database to Objects and Classes, and allowing you to communicate with your database in an Object-Oriented approach.

Hibernate was a solution to such a challenge; as it handles the communication with the database by transforming the queries and instructions set by the user, in an object oriented approach, to its equivalent SQL queries. This allows developers to work in the whole application with an Object-Oriented paradigm, while delegating the Database conversations to Hibernate.
For example, You want to insert the a new record to the table 'Lecturer'; Hibernate will enable you to
do it in a way similar to this:

Lecturer L1 = new Lecturer();
L1.setFirstName ("Fatma");
L1.setLastName("Meawad");
save(L1);

In addition to saving data, it allows you to search and Query the records of the Database.This is the so called, Object-Relational Mapping (ORM). ORM is defined by pcmag.com as “Converting data from tables in a relational database to objects and vice versa”.

Hibernate is considered the most popular ORM tool for Java. Its commonly recognized features are
- Development time reduction
- The ease of switching between different Databases.

next section is to show you the structure of a Hibernate application, and the functions of the
files and classes we will be using in our example.

Files and Classes

As mentioned in the 'About' section, hibernate handles the communication with the database; by transforming the queries and instructions set by the user, in an object oriented approach, to its equivalent SQL queries
For example,
Assume having the table “Lecturer” with columns: ID, FName, LName.


The user would like to add a new Lecturer this way:
Lecturer L1 = new Lecturer();
L1.setFirstName ("ishwar");
L1.setLastName("panjari");
save(L1);
So, first off all, we need to have a
Class representing

- Attributes representing the columns of the table. firstName, lastName
- A getter and a setter method for each attribute.
   getFirstName, setFirstName, getLastName, setLastNam.



So, how Hibernate will know that the firstName attribute, in the Lecturer object, corresponds to the
FName column, in the Lecturer Table ?
Here comes the role of the “Mapping files”. Hibernate uses these mapping files to point out which classes are representing which tables, which attributes are representing which columns , and other aspects that helps in the construction of the generated query.


It seems that every thing is now clear for Hibernate to be able to perform its job; but actually,Hibernate still needs to know how to manage the connections with the Database.It needs to know the DataSource name or you can used the native api java driver, username and password if any, the driver class, information about managing transactions, caching, and connection pooling .etc; These are called “Hibernate configurations“.

Hibernate configurations can be set either
1)Programatically or
2)in a .properties file or
3)in a .xml file

For example, you can tell hibernate about your DataSource name, username and password in one of
these ways:
1)Programmatically
Configuration config = new Configuration();
config .setProperty("hibernate.connection.url", "jdbc_URL");
config .setProperty("hibernate.connection.username","DB_Username");
config .setProperty("hibernate.connection.password","DB_Password");

2)in a .properties file containing these commands
hibernate.connection.url = jdbc_URL
hibernate.connection.username = DB_Username
hibernate.connection.password = DB_Password

3)in an XML file
<property name="connection.url">jdbc _URL</property>
<property name="connection.url">DB_Username</property>
<property name="connection.password">DB_Password</property>

To build a Hibernate application, we need:
1- Persistent classes; those are classes representing the Database entity tables.
2- Mapping files; defining persistent classes and their attributes, and their corresponding database and columns.
3- Hibernate Configurations settings; that shows hibernate how to obtain and manage the connections with the database.

Simple Example (with MySql Database).
This section is divided into two parts. The first part is a step-by-step to create a very simple Hibernate application that inserts a new record in the Database. The second part is to understand the code you have written in the application.
In this tutorial we are using Eclipse  IDE.

Part One | The Example steps:
First of all, we need to create the Database, and the table we are going to insert in.
1. Prepare your Datasource or you can used native api java driver or other java driver types and name it “UniversityDs”.
1.1 Create a new Database. To be consistent with the tutorial, name it “UniversityDS”.
1.2. Create the table “Lecturer” with columns
- ID (PK, int, not null)
- FName (nvarchar(50), null)
- LName (nvarchar(50), null)
you can use this query
Create Table Lecturer
( ID int, FName nvarchar(50), LName nvarchar(50), Primary Key (ID))


2. Create a Java Project and name it “HibernateHelloWorld”
If this is your first time using eclipse, follow these steps:
2.1. Open Eclipse. Go to the folder where you saved eclipse and double-click
2.2. Choose your workspace. Browse to the directory that you need to use as a workspace.
A workspace is the place where your projects are saved. You may use an already existing folder to function as a workspace, or create a new one by browsing to the directory that you need your workspace to be placed in (C for example), and then writing the workspace name you like (the folder will be created automatically).

3. Go to the workbench. If the Welcome page is opened, you can reach the workbench by clicking this icon.

4. Create the project.
4.1. Click file in the menu-bar / New / Project .
4.2. Select Java / Java Project
4.3. Name it “HibernateHelloWorld”
4.4. Click Finish

5. Add Hibernate Jar files
To use Hibernate, Your application needs to use some Jar files that are available in this link here.
5.1. Unzip the downloaded file.
5.2. In the Project Explorer view
(at the left-side of eclipse. If not there, Click: Window / Show view / Project Explorer)
R-Click your project / Build Path / Configure Build Path.
5.3. Add External JARs / Go to the unzipped folder - Select All / Open / Ok.

In the Files and Classes section, we said that To build a Hibernate application, we need:
1- Persistent classes. Those are classes representing the Database entity tables.
2- Mapping files. Defining persistent classes and their attributes, and their corresponding database and columns.
3- Hibernate Configurations settings. That shows hibernate how to obtain and manage the connections with the database.
4-Main Java Program-This will perform operation for eg. select,update,delete. 
Now we are going to create these three files.

1. Create The Persistent Class for the entity 'Lecturer'.
1.1 Create a class. In the Project Explorer view, R-Click your project / New / Class.
1.2. Name it 'Lecturer'.
1.3. Click Finish.
1.4. Place this code:

 public class Lecturer {  
 private int ID;  
 private String firstName;  
 private String lastName;  
 public int getID() {  
 return ID;  
 }  
 public void setID(int id) {  
 ID = id;  
 }  
 public String getFirstName() {  
 return firstName;  
 }  
 public void setFirstName(String firstName) {  
 this.firstName = firstName;  
 }  
 public String getLastName() {  
 return lastName;  
 }  
 public void setLastName(String lastName) {  
 this.lastName = lastName;  
 }  
 }  

2. Create The Mapping File for the Table 'Lecturer'
2.1. Create an XML file. In the Project Explorer view, R-Click your project / New / File.
2.2. Name it 'Lecturer.hbm.xml'.
2.3. Click Finish.
2.4. Open it with Text Editor. R-Click 'Lecturer.hbm.xml' / Open with / Text Editor.
2.5. Place this code:

 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Lecturer" table="Lecturer">  
 <id name="ID" type="int">  
 <generator class="increment"/>  
 </id>  
 <property name="firstName" column="FName" type="string"/>  
 <property name="lastName" column="LName" type="string"/>  
 </class>  
 </hibernate-mapping>  

3. Create an XML for Hibernate Configurations 'hibernate.cfg.xml'.
3.1. Create an XML file.
3.2. Name it 'hibernate.cfg.xml'.
3.3. Click Finish.
3.4. Open it with Text Editor.
3.5. Place this code:

 <?xml version='1.0' encoding='UTF-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
 <!-- ________________ To be Edited _________________ -->  
 <property name="connection.url">jdbc_URL</property>  
 <property name="connection.username">jdbc_Username</property>  
 <property name="connection.password">jdbc_Password</property>  
 <!-- _____________ End of To be Edited ______________ -->  
 <property name="connection.driver_class">  
 sun.jdbc.odbc.JdbcOdbcDriver  
 </property>  
 <property name="dialect">  
 org.hibernate.dialect.MySQLDialect</property>  
 <property name="current_session_context_class">thread</property>  
 <!-- ___________ Defining Mapping Files _____________ -->  
 <mapping resource="hibernate.hbm.xml" />  
 </session-factory>  
 </hibernate-configuration>  

3.6. Replace jdbc_URL, jdbc_Username, and jdbc_Password, with their appropriate values.
- The jdbc_URL should look like 'jdbc:odbc:UniversityDS'.
- The Username, and Password are used for MySQL Authentication. They are those you
input to connect the MySQL Database.
If you used java native driver then contain value as
<property name="connection.url">jdbc:mysql://localhost/ UniversityDS</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
But for this driver you have to add one jar file mysql-connector-java-5.1.22-bin.jar .you can download from here.

4. Finally Test your Application
4.1. Create a class.
4.2. Name it 'SimpleTest'.
4.3. Click Finish.
4.4. Place this code:

 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 public class SimpleTest {  
 public static void main(String[] args) {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Lecturer lecturer1 = new Lecturer();  
 lecturer1.setFirstName("ishwar");  
 lecturer1.setLastName("panjari");  
 session.save(lecturer1);  
 tx.commit();  
 System.out.println ("The lecturer " + lecturer1.getFirstName()+" " + lecturer1.getLastName()+  
 " is successfully added to your database");  
 }  
 }  

5. Run your application by pressing Ctrl + F11 / Java Application
6. Check your Database.

now. Proceed with reading to understand the code you have been pasting.

The application you have just created is having these files:
1. The persistent class 'Lecturer.java'.
2. Themapping file 'Lecturer.hbm.xml'.
3. The Configurations file 'hibernate.cfg.xml'.
4. The testing class 'SimpleTest.java'
Now we are going to explain the code in these files.

1. The persistent class 'Lecturer.java'.

As explained in the previous section, we need to have a Class corresponding to each entity Table in our database. Instances of this class will be used to represent Database records. So accordingly the class should be able to carry data that can exist in such records, and since the table Lecturer is having the columns:
- ID (int),
- FName (nvarchar(50)), and
- LName (nvarchar(50)).
The corresponding class should be having a variable of type 'int' and two variables of type 'String'.
In our example, they are:
- int ID
- String firstName
- String lastName
It is preferred not to provide a direct access to the variables but use accessor methods to the
variables. Thats why the instant variables are 'private' and there is a getter and a setter method for  each one. Hibernate can recognize accessor methods of the form getVariablename and
setVariablename.

2. The Mapping file 'Lecturer.hbm.xml':

The previous section showed that we need a mapping file to tell Hibernate, what Class is
representing which Table, and what Instant Variable is corresponding to which Column.
In our example, we have:
One Class 'Lecturer' that corresponds to the Table 'Lecturer', This is declared this way:
<class name="Lecturer" table="Lecturer">
The class with the name 'Lecturer' is corresponding to the table 'Lecturer'.
In this Class, there are the instant variables:
- 'firstName' and 'lastName'.
These variables are corresponding to the columns 'FName' and 'LName', This relation
can be declared this way:
<property name="firstName" column="FName" type="string"/>
<property name="lastName" column="LName" type="string"/>
- The property with the name 'firstName' is corresponding to the column 'FName'
- This property is of type 'string'.
There are other attributes that are used with the element 'property' to guide Hibernate
while creating the queries. These attributes are explained here.
- ID
This variable, in addition to corresponding to the column ID, is representing the primary
key of the table.
And since a role of a mapping file is to guide Hibernate while constructing the
queries; Hibernate has to know, from a mapping file, how the Primary key is generated.
Is it Identity, so the database will generate it ? Or the application will set it
manually ? Or Hibernate will have to generate it ? … etc.
In our example, we declared it this way:
<id name="ID" type="int">
<generator class="increment"/>
</id>
- The Primary key of the Table is represented by the instant variable with the name 'ID'.
- The generator class of the Primary Key is 'increment'. This means that Hibernate
is going to set it by incrementing the maximum ID value in the table by one. In other
words, Hibernate will select the Max ID in the table; Add 1 to it; set the ID value of the
new object to the calculated value.

3. Creating an XML for Hibernate Configurations 'hibernate.cfg.xml'

The previous section stated that hibernate needs to know some information about the database and how to manage connections with it, and that this is information can be provided
1. Programatically, or
2. in XML file, or
3. in .properties file
In our example, we used an XML file for setting Hibernate Configurations.
The file 'hibernate.cfg.xml' contained the very basic configurations needed to obtain and manage
the connections; these configurations are:
- The Datasource URL
<property name="connection.url">jdbc_URL</property>
MySQL Username and Password
<property name="connection.username">jdbc_Username</property>
<property name="connection.password">jdbc_Password</property>
- The Driver Class
<property name="connection.driver_class">
sun.jdbc.odbc.JdbcOdbcDriver
</property>

The Dialect. It tells Hibernate about the Database it is going to generate its queries according to.

Hibernate is database independent. So, whatever database we will use in our application, we need to set dialect related to that database.
For Example, suppose we are using MySQL database, then we need below dialect: org.hibernate.dialect.MySQLDialect
Suppose if we are using SQL Server database, then we need below dialect: org.hibernate.dialect.SQLServerDialect
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>

The current_session_context_class, that tells Hibernate about how to bind the session.
<property name="current_session_context_class">thread</property>
The value 'Thread' means that the session will be binded “to the thread from which openSession(...) is called”

4. The testing class 'SimpleTest.java'.

Finally, after all these preparations, we can now use Hibernate.As said before, Hibernate performs conversations with the database. These conversations arepresented by the “session”. We obtain this session from the “SessionFactory” using the method “getCurrentSession()” or “openSession()”. For the  SessionFactory, in order to be able to manage the sessions, it should be aware of the'Configurations' we have just set. So we create an object of type “Configuration” that uses 'hibernate.cfg.xml'.
So moving bottom-up, we will:
- Create the 'Configuration' object.
Configuration configuration = new Configuration();
- Ask it to compile our preset configurations.
configuration.configure();
This could have been done in the three ways we have mentioned before
- Problematically, this way
configuration.setProperty
("hibernate.connection.url", "jdbc_URL");
- In a .properties file.
By default, a new Configuration object uses properties set in 'hibernate.properties' In an XML by calling .configure method
By default, the .configure() method uses the elements in 'hibernate.cfg.xml'. If you want to name your configurations file another name, you have to specify this
file by calling one of the method's overloads, like for example:
configuration.configure("conf.xml");

- Create a SessionFactory with these configurations.
SessionFactory sessionFactory =configuration.buildSessionFactory();
- Start a DB Conversation by getting a Session
Session session = sessionFactory.getCurrentSession();
For less code, we have written the first three statements this way
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Now we have an opened conversation, we will enclose our commands in a Transaction
Transaction tx = session.beginTransaction();

tx.commit();

To be able to see the queries executed by Hibernate, add this statement to 'hibernate.cfg.xml'
<property name="hibernate.show_sql">true</property>
Now we are done with our Simple Example, we should be moving to a more Advanced Example,
but first you need to know the different 'States of objects' in a Hibernate application.

Hibernate's objects' states;


 1. Persistent state.
The object is gauranteed to be representing a database record. These are objects attached to a Hibernate session. They are objects either saved , retrived .. etc by Hibernate. In our example, the object lecturer is persistent after this statment
session.save(lecturer1)

2. Transient state.
Those are normal objects, used through out the application, and lose there values once the application is closed. In our example, the object lecturer is transient before this statment
session.save(lecturer1)

3. Detached objects.
They are objects that where once persistent (attached to a certain context), but then this context is closed. It is not guranteed that this object is reflecting the database state. In our example, the object lecturer is detached after the statment
tx.commit()

Other Operation on Database

1. AddNewLecturer for that INSERT
 This we all ready  discuss in above example

2.DeleteLecturer for the DELETE
    For Delete Record from database we need to set primary key  id value which identified the reconrd.eg
    Lecturer lecturer1 = new Lecturer();
    lecturer1.setID(1);
session.delete(lecturer1);
just replace this above three line in 'SimpleTest' program and execute.

3.EditLecturer
we UPDATE a record by setting the values of certain fields, Where the Primary key is equal to a
certain value.
The same takes place here; we have an object to be updated,
- The Primary key of the object specifies which record is to be updated, and
- The values of the object's variables represent the new record values
- EditLecturer for the UPDATE
It is the same like AddNewLecturer, except for session.save(L1), we use session.update(L1)
instead- Test it in the main method:
eg.

lecturer1.setID(1);
lecturer1.setFirstName("Fatma");
lecturer1.setLastName("ishwar");
then used method
 session.update(lecturer1);

Hibernate supports three ways for querying the database; they are:
1. Using Hibernate Query Language (HQL).
2. Using Criteria Queries.
3. Using Native SQL.
To have a quick overview on the three approaches; This is how to retrieve Lecturers whose First
Names are 'ishwar', using the three approaches:

1. HQL
Simple way:
Query namesSearch = session.createQuery("from Lecturer where firstName = 'ishwar' ");
Or Using positional parameters:
Query namesSearch = session.createQuery("from Lecturer where firstName = ? ");
namesSearch.setString(0, "ishwar");
Or Using named Parameters:
Query namesSearch = session.createQuery("from Lecturer where firstName = :fn ");
namesSearch.setString("fn", "ishwar");

Starting the query with 'from' means you are selecting the whole object. The second and the third approaches work with binding parameters. From their names, it is clear that positional parameters depend on the position of the parameter (the index of the question '?' mark with a count starting from zero), while the
named parameters depend on the parameter name.
for e.g.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 SQLQuery namesSearch = session.createSQLQuery("Select * From Lecture where FName = 'Fatma'");  
 namesSearch.addEntity(Lecture.class);  
 List<Lecture> lecturer1 = (List<Lecture>)namesSearch .list();  
 for (int i = 0; i < lecturer1.size() ; i++)  
 {  
 System.out.println( lecturer1.get(i).getFirstName() + " "+ lecturer1.get(i).getLastName());  
 }  
 }  
 }  

 2. Criteria Query
Criteria namesSearch =session.createCriteria(Lecturer.class);
namesSearch.add(Restrictions.eq("firstName", "ishwar"));
Restriction.eq represents the 'equal' restriction.
For executing above query is same like first types query program. Just u replase above statement.

3. Native SQL
SQLQuery namesSearch = session.createSQLQuery("Select *From Lecturer where FName = 'Fatma'");
namesSearch.addEntity(Lecturer.class);
.addEntity (Lecturer.class) tells Hibernate that the result is to be in the form of 'Lecturer' Objects, else the values will be selected separately (i.e. firstName, lastName are two Strings saved as two separated objects).
Note: To refer to the property 'First Name', we use the corresponding variable name 'firstName', except in the Native SQL approach, we are use the table column name FName.
All these approaches are for constructing the query ( i.e. the query is not executed yet ).
To execute the query we usually use .list() that returns a list of the results.

Writing simple query e.g.

 import javax.management.Query;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import antlr.collections.List;  
 import java.sql.*;  
 import java.util.Iterator;  
 public class RetriveData  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.openSession();  
 Transaction tx = session.beginTransaction();  
 String SQL_QUERY="from Lecture where FName = 'Fatma'";  
 Lecturer l;  
     org.hibernate.Query query = session.createQuery(SQL_QUERY);  
     session.getTransaction().commit();  
     Iterator it = query.iterate();  
     while(it.hasNext())  
     {  
       l= (Lecturer)it.next();  
       System.out.println("id: " + l.getID());  
       System.out.println("First Name: " + l.getFirstName());  
       System.out.println("last Name: " + l.getLastName());  
     }  
 }  
 }  

Relation in Hibernates (Mapping in Hibernates)

1)    Many-to-One Hibernate Mapping .
In this example you will learn how to map many-to-one relationship using Hibernate. Consider the following relationship between Course and Lecturer entity.
Eg.

According to the relationship many Course can have the same Lecturer.
On the Database level: A Course has a foreign key 'LecturerID'.
- Create the table Course; you can use this query:

Create Table Course(
ID int, Course_Title nvarchar(50), Lecturer_ID int,
Primary Key (ID), Foreign Key (Lecturer_ID) References
Lecturer)
- Insert some records in your Tables to help us while testing.
Other way first you create table and later you add foreign key .eg.
Create Table Course(
ID int, Course_Title nvarchar(50), Lecturer_ID int,
Primary Key (ID))
Adding foreign key.e.g.
Alter Course add foreign key(Lecture_ID) references Lecturer);

Create the table “Lecturer” with columns
- ID (PK, int, not null)
- FName (nvarchar(50), null)
- LName (nvarchar(50), null)
you can use this query
Create Table Lecturer
( ID int, FName nvarchar(50), LName nvarchar(50), Primary Key (ID))


On the application Level
We said before that Hibernate allows you to work in the whole application with an Object Oriented paradigm, so of course Hibernate will not represent the Lecturer teaching a Course by a 'Foreign Key'; Instead, we will be able to represent it by the whole object of the lecturer (i.e. An instant of the class 'Course' will be having an instant variable of type 'Lecturer' that represents the lecturer teaching it) this is one way for dealing with such a relation.

Create the Class 'Course'
with the instant variables:
- private int ID;
- private String title;
- private Lecturer lecturer;
And their getters and setters.
Eclipse can generate the getters and setters for you this way:
R-Click anywhere in your 'Course' Class
Select Source / Generate Getters and Setters
Select All / Ok
Create the Mapping
You can either create a new mapping file 'Course.hbm.xml' for example, or
complete working on the file 'Lecturer.hbm.xml'
Add the mapping for the 'ID' and 'title'like we have done before for the
'lecturer'.
As for the 'lecturer' variable, instead of mapping it using the element
'property', we use the element many-to-one since many courses can be
taught by one Lecturer. This is expressed this way:

<many-to-one name="lecturer" class="Lecturer"
column="Lecturer_ID"  cascade="all"/>

It can be read:
A many-to-one relation where The variable of name 'lecturer' is an instant of the class 'Lecturer' (i.e. representing a record from the table 'Lecturer' that is represented by the class 'Lecturer'). And the
corresponding foreign key column in this table, the 'Course' table, is
Lecturer_ID.

The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to all then all the operations will be cascaded. For instance when you save a Course object, the associated Lecturer object will also be saved automatically.

Add it to Hibernate configurations
If you have created a new file for the 'Course' mapping, you have to tell Hibernate about it. So add a Resource reference for it in Hibernate.cfg.xml.

<mapping resource="Course.hbm.xml" />

Now see full example bellow and Run SimpleTest1.java
1) Course.java (POJO Classes)

 public class Course {  
   private int ID;  
    private String title;  
    private Lecture lecture;  
   public int getID() {  
     return ID;  
   }  
   public void setID(int iD) {  
     ID = iD;  
   }  
   public String getTitle() {  
     return title;  
   }  
   public void setTitle(String title) {  
     this.title = title;  
   }  
   public Lecture getLecture() {  
     return lecture;  
   }  
   public void setLecture(Lecture lecture) {  
     this.lecture = lecture;  
   }  
 }  

2)Lecturer.java (POJO Classes)

 public class Lecturer {  
 private int ID;  
 private String firstName;  
 private String lastName;  
 public int getID() {  
 return ID;  
 }  
 public void setID(int id) {  
 ID = id;  
 }  
 public String getFirstName() {  
 return firstName;  
 }  
 public void setFirstName(String firstName) {  
 this.firstName = firstName;  
 }  
 public String getLastName() {  
 return lastName;  
 }  
 public void setLastName(String lastName) {  
 this.lastName = lastName;  
 }  
 }  

2)hibernate.cfg.xml

 <?xml version='1.0' encoding='UTF-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
 <!-- ________________ To be Edited _________________ -->  
 <property name="connection.url">jdbc_URL</property>  
 <property name="connection.username">jdbc_Username</property>  
 <property name="connection.password">jdbc_Password</property>  
 <!-- _____________ End of To be Edited ______________ -->  
 <property name="connection.driver_class">  
 sun.jdbc.odbc.JdbcOdbcDriver  
 </property>  
 <property name="dialect">  
 org.hibernate.dialect.MySQLDialect</property>  
 <property name="current_session_context_class">thread</property>  
 <!-- ___________ Defining Mapping Files _____________ -->  
 <mapping resource="hibernate.hbm.xml" />  
 </session-factory>  
 </hibernate-configuration>  

3)hibernate.hbm.xml

 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Lecture" table="Lecture">  
 <id name="ID" type="int">  
 <generator class="increment"/>  
 </id>  
 <property name="firstName" column="FName" type="string"/>  
 <property name="lastName" column="LName" type="string"/>  
 </class>  
 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 <generator class="increment"/>   
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <many-to-one name="lecture" class="Lecture"  
 column="Lecture_ID" cascade="all" />  
 </class>  
 </hibernate-mapping>  

4)Java Main program-Insert using Many to One Mapping

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest1  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 //for inserting value  
 Lecture lecturer1=new Lecture();  
 lecturer1.setFirstName("Fatma");  
 lecturer1.setLastName("ishwa11r");  
 Course course=new Course();  
 course.setTitle("English");  
 course.setLecture(lecturer1);  
 session.save(course);  
 tx.commit();  
 }  
 }  

5)Java Main program-Delete Operation using Many to One Mapping.

 import javax.management.Query;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import antlr.collections.List;  
 import java.sql.*;  
 import java.util.Iterator;  
 public class DeleteData  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.openSession();  
 Transaction tx = session.beginTransaction();  
 Object o = session.get(Course.class, new Integer(2));  
 Course c = (Course)o;  
 session.delete(c);  
 tx.commit();  
 }  
 }  

6)Java Main program-Update Operation using Many to One Mapping.

 import javax.management.Query;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import antlr.collections.List;  
 import java.sql.*;  
 import java.util.Iterator;  
 public class UpdateData  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.openSession();  
 Transaction tx = session.beginTransaction();  
 Course course=new Course();  
 course.setID(1);  
 course.setTitle("ENG");  
 Lecture lecturer=new Lecture();  
 lecturer.setID(3);  
 lecturer.setFirstName("english");  
 course.setLecture(lecturer);  
 session.update(course);  
 tx.commit();  
 }  
 }  



7)Java Main program-Select Operation using Many to One Mapping.
prints all Courses and their Lecturers.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest1  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 String query = "from Course crs";  
 List results = session.createQuery(query).list();  
 // ------------- Printing the content of the list ----------------  
 System.out.println (" -- Courses and Lecturers --");  
 for (int i = 0; i < results.size() ; i++)  
 {  
 Course crs = (Course)results.get(i);  
 System.out.println( crs.getTitle()+ "\t" +crs.getLecture().getFirstName());  
 }  
 System.out.println (" ---------------------------");  
 }  
 }  


2)One to Many Hibernate Mapping.
For one-to Many Mapping we will use the new entity 'Teaching Assistant', where a Course can have many TAs, while the TA is assisting in one course. So in simple language you can say that one course having more than one Teaching Assistant.e.g.


On the Database level:

1.Course table
Create Table Course(ID int, Course_Title nvarchar(50), Primary Key (ID));
2. TA(Teaching Assistant) table
An  TA has a foreign key 'CourseID'.
Create the table TA; you can use this query:
Create Table TA(
ID int, FName nvarchar(50), LName nvarchar(50),
CourseID int, Primary Key (ID), Foreign Key (CourseID) References Course)

Create the Class 'TeachingAssistant' with the instant variables:
- private int ID;
- private String firstName;
- private String lastName;
  private String CourseID;
And their getters and setters.

- Add the TAs list to Course.java,
Add the instant variable
private int ID;
private String title;
private List TAs;
Create its getter and setter methods

Create the Mapping
Again, you can either create a new mapping file 'TeachingAssistant.hbm.xml' for example, or complete working on a previously created mapping file.
Add the mappings for the 'ID' , 'firstName' and 'lastName' ,’CourseID ‘normally like
we did before.
Now Mapping for Course,ID and Course_Title is normally like we did before.
Add the TAs list mapping
This time the relation is One-to-Many (a Course can have many TAs), so we
will be using the element one-to-many.

<set name="TAs" cascade="all" >
 <key column="CourseID" />
<one-to-many class="TeachingAssistant" />
 </set>

Here CourseID is foreign key in TeachingAssistant table and TeachingAssistant is class name and ‘TAs’ is an set object name which is binding in foreign CourseID column.

•  In order to transfer 0perations on parent object to child object we need to add cascade attribute
•  By default, cascade value is none, it means even though relationship is exist, the operations we are doing on parent will not transfer to child, i mean to say hear operations are insert, delete, update
•  here we used cascade =”all” means all operations at parent object will be transfer to child. means  what ever operation you are performing to Course also it will transfer to the TeachingAssistant.
full program example

1)Course.java(POJO Class)

 import java.util.Set;  
 import antlr.collections.List;  
 public class Course {  
   private int ID;  
    private String title;  
    private Set TAs;  
   public int getID() {  
     return ID;  
   }  
   public void setID(int iD) {  
     ID = iD;  
   }  
   public String getTitle() {  
     return title;  
   }  
   public void setTitle(String title) {  
     this.title = title;  
   }  
   public Set getTAs() {  
     return TAs;  
   }  
   public void setTAs(Set tAs) {  
     TAs = tAs;  
   }  
 }  

2)TeachingAssistant.java(POJO Class)

 public class TeachingAssistant {  
   private int ID;  
   private String firstName;  
   private String lastName,CourseID;  
   public int getID() {  
     return ID;  
   }  
   public void setID(int iD) {  
     ID = iD;  
   }  
   public String getFirstName() {  
     return firstName;  
   }  
   public void setFirstName(String firstName) {  
     this.firstName = firstName;  
   }  
   public String getLastName() {  
     return lastName;  
   }  
   public void setLastName(String lastName) {  
     this.lastName = lastName;  
   }  
   public String getCourseID() {  
     return CourseID;  
   }  
   public void setCourseID(String courseID) {  
     CourseID = courseID;  
   }  
 }  


3)hibernate.hbm.xml(Hibernate mapping file)

 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <set name="TAs" cascade="all" >  
  <key column="CourseID" />  
 <one-to-many class="TeachingAssistant" />  
  </set>  
 </class>  
 <class name="TeachingAssistant" table="ta">  
 <id name="ID" type="int">  
 </id>  
 <property name="firstName" column="FName" type="string"/>  
 <property name="lastName" column="LName" type="string"/>  
 </class>  
 </hibernate-mapping>  

4)hibernate.cfg.xml(Hibernate Configuration file)

 <?xml version='1.0' encoding='UTF-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
 <!-- ________________ To be Edited _________________ -->  
 <property name="connection.url">jdbc_URL</property>  
 <property name="connection.username">jdbc_Username</property>  
 <property name="connection.password">jdbc_Password</property>  
 <!-- _____________ End of To be Edited ______________ -->  
 <property name="connection.driver_class">  
 sun.jdbc.odbc.JdbcOdbcDriver  
 </property>  
 <property name="dialect">  
 org.hibernate.dialect.MySQLDialect</property>  
 <property name="current_session_context_class">thread</property>  
 <!-- ___________ Defining Mapping Files _____________ -->  
 <mapping resource="hibernate.hbm.xml" />  
 </session-factory>  
 </hibernate-configuration>  

5) Java Main program-Insert Operation using One to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Course c =new Course();  
 c.setID(104);  
 c.setTitle("java4s");  
 //creating 3 child objects  
 TeachingAssistant t1=new TeachingAssistant();  
 t1.setID(510);  
 t1.setFirstName("ishwar");  
 t1.setLastName("panjari");  
 TeachingAssistant t2=new TeachingAssistant();  
 t2.setID(511);  
 t2.setFirstName("ishwar1");  
 t2.setLastName("panjari1");  
 // adding child objects to set, as we taken 3rd property set in parent  
 Set s=new HashSet();  
 s.add(t1);  
 s.add(t2);  
 c.setTAs(s);  
 session.save(c);  
 tx.commit();  
 }  
 }  


6)Java Main program-Delete Operation using One to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Object o = session.get(Course.class, new Integer(104));  
 Course c = (Course)o;  
 session.delete(c);  
 tx.commit();  
 }  
 }  

7)Java Main program-Update Operation using One to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class DeleteData  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Course course=new Course();  
 course.setID(1);  
 course.setTitle("ENGLish");  
 TeachingAssistant t1=new TeachingAssistant();  
 t1.setID(510);  
 t1.setFirstName("Panjari ishwar");  
 Set s=new HashSet();  
 s.add(t1);  
 course.setTAs(s);  
 session.update(course);  
 tx.commit();  
 }  
 }  

8)Java Main program-Select Operation using One to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 org.hibernate.Query qry =session.createQuery("from Course c");  
 List l=qry.list();  
 Iterator it = l.iterator();  
 while(it.hasNext())  
 {  
 Object o = it.next();  
 Course c = (Course)o;  
 System.out.println(c.getID()+ " " +c.getTitle());  
 Set s= c.getTAs();  
 Iterator it1=s.iterator();  
 while(it1.hasNext())  
 {  
 TeachingAssistant t = (TeachingAssistant) it1.next();  
 System.out.println(t.getID()+" "+t.getFirstName()+ " "+ t.getLastName()+""+t.getCourseID());  
 }  
  }  
 tx.commit();  
 }  
 }  

 

3)Many-To-Many Hibernate Mapping.

In the previous relations, we where choosing between either to map it many-to-one or one-to-many.i.e., for the Lecturer and Course, we had the choice to create a Lecturer instant variable for the class In this example you will learn how to map many-to-many relationship using Hibernate. Consider the following relationship between Student and Course entity.


According to the relationship a student can enroll in any number of courses and the course can have any number of students.

Course, or create a List of Courses for the class Lecturer. Actually, we could have combined both together; this is called 'Bidirectional mapping'. In a Bidirectional mapping, the relation is represented in both sides. (i.e., The Lecturer has a List of Courses, and the Course has a Lecturer object). Mapping the relation from one side, like we have been doing, is called 'Unidirectional mapping'.

We will try the Bidirectional mapping along with the Many-to-Many relation, by adding to our example the entity Student, where a Student can have many Courses and a Course can have many Students.

On the Database level: an Enroll table represents the relation
- Create the table Student; you can use this query:
Create Table Student(
ID int, FirstName nvarchar(50), LastName nvarchar(50),Primary Key (ID))

- Create Table Course(ID int, Course_Title nvarchar(50), Primary Key (ID))
Create the table Enroll; you can use this query:

Create Table Enroll (
CourseID int, StudentID int, Foreign Key (CourseID) References Course,
Foreign Key (StudentID) References Student)

On the application level
This time we will be creating the Class Student, adding to it a List of Courses; and adding to the class Course, a List of Students.

Create the Class 'Student'
with the instant variables:
- private int ID;
- private String firstName;
- private String lastName;
- private List courses;
And their getters and setters.

Create the Class 'Course'
with the instant variables:
- private int ID;
- private String title;
 -private List students;

And their getters and setters.

- Create the Mapping Student.hbm.xml file   
Add the mappings for the 'ID' , 'firstName' and 'lastName' normally like
we did before.
Add the mapping for the 'courses'
This is a many-to-many relation, so we will be using the element many-to-many,
and again we are using a List,

<set name="courses" table="Enroll">
<key column="StudentID" />
<many-to-many column="CourseID" class = "Course"/>
</set>
It can be read:
The list with the name "courses" is representing a many-to-many relation with the table represented by the class "Course", where the relation is represented by the table "Enroll". The key of this Class
(Student) in the relation is StudentID , and the key of the class "Course" is CourseID.

Create the Mapping Course.hbm.xml file
Add the mappings for the 'ID' and ‘title’ normally like
we did before.
- Add the 'students' list mapping
<set name="students" table="Enroll" >
<key column="CourseID" />
<many-to-many column="StudentID" class = "Student"/>
</set>

It can be read:
The list with the name "students" is representing a many-to-many relation with the table represented by the class "Student", where the relation is represented by the table "Enroll". The key of this Class (Course) in the relation is CourseID , and the key of the class "Student" is StudentID.
Add it to Hibernate configurations
Now full example Many to Many Operation.

1)student.java

 import java.util.Set;  
 public class Student {  
   private int ID;  
    private String firstName;  
    private String lastName;  
    private Set courses;  
   public int getID() {  
     return ID;  
   }  
   public void setID(int iD) {  
     ID = iD;  
   }  
   public String getFirstName() {  
     return firstName;  
   }  
   public void setFirstName(String firstName) {  
     this.firstName = firstName;  
   }  
   public String getLastName() {  
     return lastName;  
   }  
   public void setLastName(String lastName) {  
     this.lastName = lastName;  
   }  
   public Set getCourses() {  
     return courses;  
   }  
   public void setCourses(Set courses) {  
     this.courses = courses;  
   }  
 }  

2)Course.java

 import java.util.Set;  
 import antlr.collections.List;  
 public class Course {  
   private int ID;  
    private String title;  
    private Set students;  
   public int getID() {  
     return ID;  
   }  
   public void setID(int iD) {  
     ID = iD;  
   }  
   public String getTitle() {  
     return title;  
   }  
   public void setTitle(String title) {  
     this.title = title;  
   }  
   public Set getStudents() {  
     return students;  
   }  
   public void setStudents(Set students) {  
     this.students = students;  
   }  
 }  

3)Student.hbm.xml

 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Student" table="student">  
 <id name="ID" type="int">  
 </id>  
 <property name="firstName" column="FName" type="string"/>  
 <property name="lastName" column="LName" type="string"/>  
 <set name="courses" table="Enroll" inverse="false" cascade="all">  
 <key column="StudentID" />  
 <many-to-many column="CourseID" class = "Course"/>  
 </set>  
 </class></hibernate-mapping>  

4)Course.hbm.xml

 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <set name="students" table="Enroll" cascade="all" >  
 <key column="CourseID" />  
 <many-to-many column="StudentID" class = "Student"/>  
 </set>  
 </class>  
 </hibernate-mapping>  

5)Hibernate.cfg.xml

 <?xml version='1.0' encoding='UTF-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
 <!-- ________________ To be Edited _________________ -->  
 <property name="connection.url">jdbc:mysql://localhost/univercity</property>  
 <property name="connection.username">root</property>  
 <property name="connection.password"></property>  
 <!-- _____________ End of To be Edited ______________ -->  
 <property name="connection.driver_class">  
 sun.jdbc.odbc.JdbcOdbcDriver  
 </property>  
 <property name="dialect">  
 org.hibernate.dialect.MySQLDialect  
 </property>  
 <property name="show_sql">true</property>  
 <property name="current_session_context_class">thread</property>  
 <!-- ___________ Defining Mapping Files _____________ -->  
 <mapping resource="Student.hbm.xml" />  
 <mapping resource="Course.hbm.xml"/>  
 </session-factory>  
 </hibernate-configuration>  

6) Java Main program-Insert Operation using Many to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Student s1=new Student();  
 s1.setID(20);  
 s1.setFirstName("panjari");  
 s1.setLastName("ishwar");  
 Student s2=new Student();  
 s2.setID(21);  
 s2.setFirstName("Raol");  
 s2.setLastName("Jaydip");  
 Course c1=new Course();  
 c1.setID(10);  
 c1.setTitle("SE");  
 Course c2=new Course();  
 c2.setID(11);  
 c2.setTitle("Ds");  
 Set s =new HashSet();  
    s.add(c1);  
    s.add(c2);  
 s1.setCourses(s);  
 s2.setCourses(s);  
  session.save(s1);  
  session.save(s2);  
 tx.commit();  
 }  
 }  

7) Java Main program-Select Operation using Many to Many Mapping.
Display Courses of Student

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest1  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 List stuList = session.createQuery("from Student").list();  
 for (Iterator iterator = stuList.iterator(); iterator.hasNext();)  
 {  
   Student student = (Student) iterator.next();  
   System.out.println("Student Name " + student.getFirstName());  
   Set course=student.getCourses();  
     Iterator<Course> it=course.iterator();  
     while(it.hasNext())  
     {  
       Course c=it.next();  
       System.out.println("the value is"+c.getTitle());  
     }  
 }  
 }  

8) Java Main program-Select Operation using Many to Many Mapping.
Display students of course

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest21  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 List crsList = session.createQuery("from Course").list();  
 for (Iterator iterator = crsList.iterator(); iterator.hasNext();)  
 {  
   Course course = (Course) iterator.next();  
   System.out.println("Course Name " + course.getTitle());  
   Set student=course.getStudents();  
     Iterator<Student> it=student.iterator();  
     while(it.hasNext())  
     {  
       Student s=it.next();  
       System.out.println("the value is"+s.getFirstName());  
     }  
 }  
 }  
 }  

9) Java Main program-Update Operation using Many to Many Mapping.

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Student s1=new Student();  
 s1.setID(20);  
 s1.setFirstName("panjar S");  
 s1.setLastName("ishwar");  
 Student s2=new Student();  
 s2.setID(21);  
 s2.setFirstName("Raol J");  
 s2.setLastName("Jaydip");  
 Course c1=new Course();  
 c1.setID(10);  
 c1.setTitle("SE new ");  
 Course c2=new Course();  
 c2.setID(11);  
 c2.setTitle("Ds new");  
 Set s =new HashSet();  
    s.add(c1);  
    s.add(c2);  
 s1.setCourses(s);  
 s2.setCourses(s);  
  session.update(s1);  
  session.update(s2);  
 tx.commit();  
 }  
 }  

10) Java Main program-Delete Operation in Association table in Many to Many Mapping.
Delete in Many to Many Mapping
This following example remove entry from association table.here association table name is enroll table.
e.g.

Student table containt Data
ID   FName    LName

20    panjari    ishwar
21    Raol    Jaydip

Course  table containt Data
ID  Course_Title

10    SE
11    Ds
   
Enroll Table contain Data(This store the foreign key of Student and Course table).This table calles association table.
CourseID   StudentID
       10       20       
       11       20
       10       21
       11       21

Now using following example we remove the entry from enroll table where CourseID=10 and StudentID=20..

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Student student = (Student)session.get(Student.class, new Integer(20));  
 Course course=(Course)session.get(Course.class,new Integer(10));  
 course.getStudents().remove(student);  
 student.getCourses().remove(course);  
  tx.commit();  
 }  
 }  
Now in database.
Student table containt Data
ID  FName  LName

20    panjari    ishwar
21    Raol    Jaydip

Course  table containt Data
ID   Course_Title
10    SE
11    Ds

   
Enroll Table contain Data
CourseID  StudentID  
11             20
10             21
11             21

So we remove 10  courseID and 20 from studentID from Enroll table.

11) Java Main program-Delete Operation in Many to Many Mapping.

The assume your database contain value with following table.

Student table contain Data
ID   FName    LName
20    panjari    ishwar
21    Raol    Jaydip

Course  table containt Data
ID  Course_Title
10    SE
11    Ds

Enroll Table contain Data(This store the foreign key of Student and Course table).This table calles association table.

CourseID   StudentID
       10       20      
       11       20
       10       21
       11       21

Now e.g  for remove studentId=20 from student;
Here if you remove 20 from Student table then automatically it will remove related courseID fromfrom course table and that courseID also related to StudentID so it will remove that also.so in this case if you remove 20 studentID from student then the above three table contain no row.

following java Main program which remove studentID=20,

 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleDelete  
 {  
 public static void main(String[] args)  
 {  
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
   Session session = sessionFactory.getCurrentSession();  
   Transaction tx = session.beginTransaction();  
   Student student = (Student)session.get(Student.class, new Integer(20));  
   session.delete(student);  
   tx.commit();  
 }  
 }  

After executing above program the three tables contain no row.



* inverse Keyword in hibernate.

In this section, you will learn how to use inverse keyword in Hibernate.

The inverse keyword is always used in One-to-Many and Many-to-Many relationship, Many-to-One doesn't have this keyword. It tells us which side is the relationship owner. In a relation (One-to-Many / Many-to-Many) , relationship owner is in charge of the relationship and handle the relationship among the two.

In simple language inverse keyword  is used for deciding the which table responsible for store the foreign key. whether parent will store foreign key in child table or child table responsible to store foreign key.

When you not specify any inverse keyword by default is an false value so parent has responsibility to store foreign key in child table.

The keyword  inverse=true means the related table is relationship owner and inverse=false means table is not the relationship owner.

The inverse  keyword tells Hibernate which table is the relationship owner between the two tables and the class related to the relationship owner table will UPDATE the relationship.Consider the below example, the Courese and TeachingAssistant table has a one-to-many relationship.




Here ID of course is an primary key and CourseID in Teaching assistants (TAs) is an foreign key.
Here inverse key word value will decide that whether Course store foreign key CourseID in TAs table or TAs table itself store the CourseID.


1)Eg. for inverse=”false”

The inverse keyword related with foreign key so it’s used with the collection. Here I am using collection set so following example put inverse value false in the collection set.

Your hibernate mapping file.


 <?xml version="1.0"?>  
 <!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
 <hibernate-mapping>  
 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <set name="TAs" inverse="false" >  
  <key column="CourseID" />  
 <one-to-many class="TeachingAssistant" />  
  </set>  
 </class>  
 <class name="TeachingAssistant" table="ta">  
 <id name="ID" type="int">  
 <!--<generator class="increment"/>-->  
 </id>  
 <property name="firstName" column="FName" type="string"/>  
 <property name="lastName" column="LName" type="string"/>  
 <property name="CourseID" column="CourseID" insert="false" />  
 </class>  
 </hibernate-mapping>  

Your main java program.(insert Operation)
 import javax.management.Query;  
 import net.sf.hibernate.Criteria;  
 import net.sf.hibernate.expression.Criterion;  
 import org.hibernate.SQLQuery;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 import org.hibernate.criterion.Restrictions;  
 import java.util.*;  
 public class SimpleTest  
 {  
 public static void main(String[] args)  
 {  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
 Session session = sessionFactory.getCurrentSession();  
 Transaction tx = session.beginTransaction();  
 Course c =new Course();  
 c.setID(104);  
 c.setTitle("java4s");  
 //creating 2 child objects  
 TeachingAssistant t1=new TeachingAssistant();  
 t1.setID(510);  
 t1.setFirstName("ishwar");  
 t1.setLastName("panjari");  
 TeachingAssistant t2=new TeachingAssistant();  
 t2.setID(511);  
 t2.setFirstName("ishwar1");  
 t2.setLastName("panjari1");  
 // adding child objects to set  
 Set s=new HashSet();  
 s.add(t1);  
 s.add(t2);  
 c.setTAs(s);  
 session.save(c);  
 session.save(t1);  
 session.save(t2);  
 tx.commit();  
 }  
 }  
After executing above program Hibernate execute following query.
Hibernate: insert into Course (Course_Title, ID) values (?, ?)
Hibernate: insert into ta (FName, LName, ID) values (?, ?, ?)
Hibernate: insert into ta (FName, LName, ID) values (?, ?, ?)
Hibernate: update ta set CourseID=? where ID=?
Hibernate: update ta set CourseID=? where ID=?

Here Three insert query that is first one insert into course table and second and third is an insert into the TAs table.
Now You set the inverse=”false” so owner has responsible for store the foreign key in child table. Here Course is an owner and TAs is an Child table
So that’s why two update query executing by Course for storing foreign key in TAs Tables.

The database Contains value.
Course table
ID     Course_Title
104    java4s

TA (Teaching Assistant) table  
ID  FName  LName  CourseID
510    ishwar    panjari        104
511    ishwar1  panjari1       104


Here Foreign key 104 is store in TA(Child Table).

2)E.g.inverse=”true”
You used the above hibernate file just you make it true value of inverse keyword.
 <set name="TAs" inverse="true" >  
  <key column="CourseID" />  
 <one-to-many class="TeachingAssistant" />  
  </set>  

Now your java main program is same as above and if you execute then Hibernate will execute the following query.
Hibernate: select course0_.ID as ID0_, course0_.Course_Title as Course2_0_ from Course course0_
Hibernate: insert into Course (Course_Title, ID) values (?, ?)
Hibernate: insert into ta (FName, LName, ID) values (?, ?, ?)
Hibernate: insert into ta (FName, LName, ID) values (?, ?, ?)

Now see only insert query execute by Hibernate because now owner is an Child table(TAs) so storing foreign key responsibility by TAs table.
The database Contains value.
Course table
    ID     Course_Title    
    104    java4s   

                           
TA Table
ID  FName      LName     CourseID

510    ishwar      panjari       NULL
511    ishwar1    panjari1    NULL

Now see CourseID is contain NULL value.
Now if you want to store CourseID in TA table then you have to map CourseID in mapping file and set value by the object of TAs class.then you will able to store foreign key in TAs table.

*Difference Between cascade and inverse Keyword

Cascade : In Hibernate the cascade option is used for defining the Owner in the relationship between the associated objects. It is an optional attribute that may be used to specify that which operation should be cascaded. Cascade has the various options "all ", " save | update | delete | merge " that may be used with either of the single option or may be used with the multiple options. Cascade decides the same operation done on the parent object is done on the associated object at the same time. A keyword "cascade" is generally used when there is a mapping does for the collection to handle the state of collection automatically.
NOTE : When you will use the cascade with 'all' option it means the owner class has all the manipulation facility that it can apply on the relationship from the parent object to the associated object.
Example of Cascade :
A mapping file that contains the mapping of collection mapping of the cascade attribute will be as follows :

 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <set name="TAs" cascade="all">  
  <key column="CourseID" />  
 <one-to-many class="TeachingAssistant" />  
  </set>  
 </class>  

Inverse : In Hibernate an inverse keyword is used in the hibernate mapping file for maintaining the relationship of the parent and the associated child object. This keyword is responsible for managing the insert / update of the foreign key column. An inverse keyword has the Boolean value "true/false". Default value of this keyword is 'false' it means the parent class is responsible for saving/updating the child and it's relationship. And when the keyword inverse is set to the 'true' it means an associated subclass is responsible for saving/updating itself.
NOTE : An inverse keyword is always used with the one-to-many and many-to-many. It doesn't work with many-to-one relationship.
Example :
A hibernate mapping file into which the inverse keyword is used as :

 <class name="Course" table="Course">  
 <id name="ID" type="int">  
 </id>  
 <property name="title" column="Course_Title" type="string"/>  
 <set name="TAs" inverse="true" >  
  <key column="CourseID" />  
 <one-to-many class="TeachingAssistant" />  
  </set>  
 </class>  

if inverse = "true" : In such case according to the above given example TAs(Teaching Assistant) will be acted as owner and the Course  will not be updated.
if inverse = "false" : In Hibernate the default value of inverse attribute is set to ‘false’ in such case according to the above given example Course is the owner and it will update the relationship.

No comments:

Post a Comment