Monday, 11 March 2019

Hibernate - Difference between update() and merge() method

Hibernate - Difference between update() and merge() method:
============================================================

Some points of update() method:
------------------------------------
1. it returns void (means will NOT return any value)
2. It doesn't check the record in the database table.
3. It performs directly update query on the database - so if record doesn't exist then it throw the exception.

Limitations of update() method
---------------------------------
1. ONLY non-primary_key column we can update.
2. Complete record we need to update. It is NOT possible to update one column for one record.

For example:

Suppose we have studentdb2 table with some records:
s_roll name course fees contact
7901 Bhupender MCA 23000 9891297115
7902 Ram Kumar BCA 12000 1223344567

Bean class:
public class Student {
private int roll;
private String name, course, contact;
private float fees;
//getter & setter methods
}

Now with above scenarios if we use update method like:

PROBLEM 1:
==========================
Student st=new Student();
st.setRoll(7901);
st.setName("Bhupender Dagar");
ses.update(st);//here ses is the Session object here.

Note: At this moment what will happen - course, fees and contact column value will be set to null.
After this operation studentdb2 table will look like this:
s_roll name            course fees contact
7901 Bhupender Dagar null         null null
7902 Ram Kumar BCA 12000 1223344567

So, be take care to perform update() method. "Complete record we need to update. It is NOT possible to update one column for one record"

PROBLEM 2:
==========================
If I use update() method with get() or load() with same record then it thow the exception. i.e duplicate object
associate with the same session.
For example:

/*
Below line record will fetch data from studentdb2 table and create same clone copy with bean class object and save this object in Session object.
*/
Student st=(Student)ses.get(7901);

Now after this if I perform update method like:
Student st1=new Student();
st1.setRoll(7901);
st1.setName("Bhupender Dagar");
ses.update(st1);//At this line an exception will occur because already this object present in
//session object.
//At this moment HB will try to save st1 in Session object and will find already same object
//there. So duplicate object find exception throw at run time.


Note: At this moment we can use merge() method:
ses.merge(st1);//At this line HB will merge the st1 to st in Session and then perform the update //operaion successfully. SO NO any exception will throw at this moment.




PROBLEM 1 - with merge() method:
============================
Student st=new Student();
st.setRoll(7901);
st.setName("Bhupender Dagar");
ses.merge(st);//here ses is the Session object here.

Note: At this moment what will happen - course, fees and contact column value will be set to null.
After this operation studentdb2 table will look like this:
s_roll name             course fees contact
7901 Bhupender Dagar null         null null
7902 Ram Kumar BCA 12000 1223344567

So, be take care to perform merge() method. "Complete record we need to update. It is NOT possible to update one column for one record"
So at this moment merge() and update() will set null values.


Some points of merge() method:
--------------------------------------------------------------------------
1. it returns void value.
2. Before update the record it checks the record in the database table.
3. If record find and data is different - then it perform update query.
4. If record find and data are same - then it will NOT perform update query.
5. You can use merge() method with get() and load() with same record.

Hibernate CURD Operations PART-1

CURD Operations in Hibernate:
=====================================
1. Insert Opeartion
-----------------------------
->by save() method
->by persist() method
-> by saveOrUpdate() method

For example:

by save() method:
----------------------------
1. It return the PK.

by persist() method
1. it returns void (will NOT return any value)

by saveOrUpdate() method
------------------------------
1. If record doesn't present in db table then it will perform save operation.
2. If record present in db table then it will perform update operation.
3. It will check record by based on PK.
4. It returns void (will NOT return any value)






2. Update Opeartion
-------------------------------
1. by update() method
2. by saveOrUpdate() method
3. by merge() method


by update() method
--------------------------------
1. HB directly perform update command based on PK.
2. If record doesn't exist in table based on PK then exception will throw at run time.
3. If bean class object data and table data are same the unnecessary update query will be performed by
the HB.
4. upadate() method NOT at any cost will peform upadate operation successfully.
5. return type is void

by merge() method
---------------------------
merge() method at any cost peform upadate operation successfully.
return type is void

Case 1:
If record present in table
->If data is different then HB - select and upadte
->If data is same then HB - select

Case 2:
If record NOT present in table
->First HB - select (check the data)
->HB - insert




3. Delete Opeartion
-------------------------------
1. by delete() method
Case 1: If record exist in the table
->HB - Select and then delete

Case 2: If record NOT exist in the table

->HB perform only select for check the record



Introduction - Hibernate Mapping File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd"> 
<hibernate-mapping>
<class name="bean.Student" table="studentdb2">  
    <id name="roll" column="s_roll">
    <generator class="assigned"/>
    </id> 
            
    <property name="name"/>  
    <property name="course"/>  
        <property name="fees"/>
        <property name="contact"/>  
  </class>  
</hibernate-mapping>
=======================================================================
1. <hibernate-mapping>: Mapping file start by this tag.
We can map multiple bean class inside one <hibernate-mapping> tags according to the requirements.

2. <class name="bean.Student" table="studentdb2"> : This tags is used to map the bean class to the DB Table.
-->table="studentdb2" - It is optional. If we don't use then HB bydefault map bean class to the DB Table by SAME Name as your POJO/Bean class name.

-->In my case "Student" bean class will map to the "studentdb2" DB Table.

3.
<id name="roll" column="s_roll">
<generator class="assigned"/>
</id>

<id> tag is used to define the primary key on the DB Table.
Here 
->name="roll" - roll is my bean class member variable.
->column="s_roll" - s_roll is my DB Table column which is define as Primary Key. It is Optional. If we don't use
then HB bydefault map to same as varaible name.

<generator class="assigned"/>: It is optional. We will discuss later about generator classes.

4. <property name="name"/> :
It is used to map the bean class variable to the noram DB Table column.
Also we can use by below:
<property name="name" column="s_name"/>: Here name variable map to the s_name column.
If we don't use column attribute then HB bydefault map to same as varaible name.



Introduction - Hibernate Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
<session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/bs</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">7901</property>  
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>  
    <property name="show_sql">true</property>
    <mapping resource="Student.hbm.xml"/> 
    </session-factory>  
</hibernate-configuration> 

=======================================================================
More About Configuration File:

Line #1. 
<?xml version="1.0" encoding="UTF-8"?> : This line shows the document type and version.
Most of xml files start with this line.

Line #2.
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">:
The DTD in the hibernate jar is a good way to know what are the attributes that can be included and the expected name for that tag.

Note: DTD is vary HB version to version.

Line #6.
<hibernate-configuration>: Each configuration file start by this tag.
Note: ONLY one configuration file is enough for per project.
We can configure more than one DB connection by single configuration file.

Line #7.
<session-factory> : For each DB configure we need ONE session-factory.
If we configure HB application by two DB then we need two <session-factory> tags.

Line #8.
<property name="hbm2ddl.auto">update</property>: This lines performs auto DDL opeartion.
We will discuss later about this line.
This is optional if we don't use then we before run the program we have to create DB Tables manually.

Line #9.
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>: 
hibernate.dialect property makes Hibernate to generate the appropriate SQL statements for the chosen database. Dialect is the SQL dialect that your database uses. Hibernate uses "dialect" configuration to know which database you are using so that it can convert hibernate query to database specific query.

For MySQL-5 or Lower version:
org.hibernate.dialect.MySQL5Dialect

Above For MySQL-5:
org.hibernate.dialect.MySQL8Dialect

For Oracle Database:
org.hibernate.dialect.OracleDialect

Line #10.
<property name="connection.url">jdbc:mysql://localhost:3306/bs</property>  : This lines defines the URL for the Database:

For mysql:
jdbc:mysql://localhost:3306/bs      Note: bs is database name, so you can change accordingly

For Oracle:
jdbc:oracle:thin:@localhost:1521:xe   Note: it is for TYPE-IV driver


Line #11.
<property name="connection.username">root</property> : User name of your database.

Line #12.
<property name="connection.password">7901</property> : Password of the database.

Line #13.
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>  : Path of your driver class.
Note: Please check the driver PATH in your Database jar files:
MOSTLY:
For mysql5 or lower version:
com.mysql.jdbc.Driver

For Oracle:
oracle.jdbc.driver.OracleDriver

Line #14.
<property name="show_sql">true</property> : It is optional. If we used this line then it show the sql commands on the console that Hibernate internally used.

Line #15.
<mapping resource="Student.hbm.xml"/> : It is used to add the mapping file.
We can add many mapping files for example:
<mapping resource="Student.hbm.xml"/>
<mapping resource="Employee.hbm.xml"/>
<mapping resource="Phone.hbm.xml"/>



Hibernate First Application Using Mapping File

Hibernate First Application Using Mapping File

Steps to create Hibernate First Application:
===================================================
1. Create Dynamic Web Project
2. Add HB Jars in lib folder
3. Create Bean/POJO class
4. Create Hibernate Configuration File
5. Create Mapping File
6. Create Test class for test the functionality



1. Create Dynamic Web Project

2. Add HB Jars in lib folder:
-> Download all the jars file https://drive.google.com/file/d/1LRzOK-L6hDRip3LJcDw112pZUA5qft6d/view?usp=sharing
--> Extract all jars files
--> Copy all jars files
--> Paste in lib folder

NOTE - Also add the DATABASE Jars (According to DB what you are using)

After paste lib folder will look like this:

3. Create package 
goto ->Java Resource->src. Then right click on src folder:

4. In my case I create package name "bean" - You can take any package name (But it should be valid)

5. Create bean class

package bean;

public class Student {
private int roll;
private String name;
private String course;
private float fees;
private String contact;
public Student(int roll, String name, String course, float fees) {
this.roll=roll;
this.name=name;
this.course=course;
this.fees=fees;
}
public Student(int roll, String name, String course, float fees, String conact) {
this(roll, name, course, fees);
this.contact=contact;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Student() {}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public float getFees() {
return fees;
}
public void setFees(float fees) {
this.fees = fees;
}
}


6. Create Hibernate Configuration File:
Path - You can save configuration file anywhere in the project but I would recommended to save in src folder by "hibernate.cfg.xml" name.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
<session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/bs</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">7901</property>  
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>  
    <property name="show_sql">true</property>
    <mapping resource="Student.hbm.xml"/> 
    </session-factory>  
</hibernate-configuration>  
 
NOTE - We will discuss more about configuration file in next blog.

7. Create Mapping File
Path - You can save mapping file anywhere in the project but I would recommended to save in src folder by "Bean_Class_Name.hbm.xml" name.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd"> 
<hibernate-mapping>
<class name="bean.Student" table="studentdb2">  
    <id name="roll" column="s_roll">
    <generator class="assigned"/>
    </id> 
            
    <property name="name"/>  
    <property name="course"/>  
        <property name="fees"/>
        <property name="contact"/>  
  </class>  
</hibernate-mapping>


NOTE - We will discuss more about mapping file in next blog.


7. Create Test class - to test the functionality

package test; //Make sure you will create test package 

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import bean.Student;

public class Test {

public static void main(String[] args) {
//1. create Configuration class object
Configuration cfg = new Configuration();
//2. config the configuration file
cfg.configure("hibernate.cfg.xml");
//3. create SessionFactory object
SessionFactory sf=cfg.buildSessionFactory();
//4. Create Session Object
Session ses=sf.openSession();
//4. if you wand to DDL operation the we need to start the TX
Transaction tx=ses.beginTransaction();
Student st=new Student();
st.setCourse("BCA");
st.setName("Bhupender");
st.setRoll(7904);
st.setFees(23000);
st.setContact("9891297115");
ses.persist(st);
tx.commit();
ses.close();
try {
Thread.sleep(20*1000);
}
catch(Exception e) {}
sf.close();
System.out.println("Inserted!!!");
}

}

8. Run the file

After run you will see record will insert in the database table.





Hibernate Jars File

Download Hibernate 5 Jars File by below link;

https://drive.google.com/file/d/1LRzOK-L6hDRip3LJcDw112pZUA5qft6d/view?usp=sharing

What is Hibernate - Hibernate Introduction


In this tutorial am going to explain, why Hibernate came into picture though we have JDBC for connecting to the database, and what is this hibernate frame work first let us see what are the draw backs of JDBC


Draw Backs of JDBC:

  • In JDBC, if we open a database connection we need to write in try, and if any exceptions occurred catch block will takers about it, and finally used to close the connections.
  • here as a programmer we must close the connection, or we may get a chance to get our of connections message…!
  • Actually if we didn’t close the connection in the finally block, then jdbc doesn’t responsible to close that connection.
  • In JDBC we need to write Sql commands in various places, after the program has created if the table structure is modified then the JDBC program doesn’t work, again we need to modify and compile and re-deploy required, which is tedious.
  • JDBC used to generate database related error codes if an exception will occurs, but java programmers are unknown about this error codes right.
  • In the Enterprise applications, the data flow with in an application from class to class will be in the form of objects, but while storing data finally in a database using JDBC then that object will be converted into text.  Because JDBC doesn’t transfer objects directly.
In order to overcome above problems,  Hibernate came into picture..!


What is Hibernate:

Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects.  Hibernate is the open source light weight tool given by Gavin King.
Hibernate is a non-invasive framework,  means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...