Hibernate by Naveen
Hibernate by Naveen
Basics
Project Structure:
Student.java
package beans;
public class Student {
private int id;
private String email;
private String name;
private int marks;
private int rank;
private String fname;
public Student(){ }
//Setters and Getters
}
student.hbm.xml
<!-- mapping file -->
<hibernate-mapping>
<class name="beans.Student" table="student007"
schema="system">
<id name="id" />
<!--to create composite Primary-key use <composite-
id> tag as follows-->
<!--
<composite-id>
<key-property name="id" column="sid">
<composite-id />
-->
<!-- property name="keyid" /-->
<property name="name" />
<property name="email" />
<property name="marks" />
<property name="rank" not-null="true" />
<property name="fname" />
<!--property name=mname /-->
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!-- configuration file -->
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDr
iver</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1
521:xe</property>
<property
name="connection.username">system</property>
<property
name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property
name="dialect">org.hibernate.dialect.OracleDialect<
/property>
<property name="hbm2ddl.auto">validate</property>
<!-- <property
name="hbm2ddl.auto">UDPATE</property> -->
<!-- <property
name="hbm2ddl.auto">VALIDATE</property> -->
<!-- <property name="hbm2ddl.auto">CREATE-
DROP</property> -->
<!-- to show what happen internally like
create/drop table add follow property -->
<property name="show_sql">true</property>
<mapping resource="resources/student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Client.java
package test;
import …*;
public class Client {
public static void main(String[] args) {
Student st=new Student();
st.setId(112);
st.setName("abc");
st.setEmail("[email protected]");
st.setMarks(500);
//state of st (object of Student) is Transient
/*below three lines will create table automatically
if <property name="hbm2ddl.auto">create</property>
is included in hibernate.cfg.xml*/
try{
Configuration cfg=new Configuration();
cfg.configure("resources/hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
sf.close();
}catch(Exception e){
e.printStackTrace();
}
//Session s=sf.openSession();
//s.save(st);
//state of st (object of Student) is Persistent
//s.beginTransaction().commit();
//state of st (object of Student) is Permanent
//s.evict(st);
//st (the object of Student) is in detached state
//st (the object of Student) Will be removed from
Persistent
//then gc(garbage collector) will collect ur
student object
System.out.println("Action done");
}
}
Object State
There are four states of an object
1. Transient : when an object is created; the object is not associated with hibernate session.
Student st=new Student(111,"abc","[email protected]",500);
2. Persistent : an object that is associated with hibernate session
s.save(st);
3. Permanent : when txn is committed.
t.commit();//object moved to db
4. Object which is just removed from hibernate session is called as detached object. The state of
the detached object is called as detached state.When the object is in detached sate then it
contain identity but you can’t do persistence operation with that identity.
Any changes made to the detached objects are not saved to the database. The detached object
can be reattached to the new session and save to the database using update, saveOrUpdate and
merge methods.
Consider the below example:
}
}
Asdf
Project Structure :
Students.java
package beans;
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver
</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe
</property>
<property name="connection.username">system</property>
<property name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.OracleDialect
</property>
<!-- property
name="dialect">org.hibernate.spatial.dialect.oracle.OracleSp
atial10gDialect</property-->
<mapping resource="resources/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Student" table="student007" schema="system">
<id name="id" column="sid"/>
<property name="name" column="sname"/>
<property name="email" column="semail"/>
<property name="marks" column="smarks"/>
</class>
</hibernate-mapping>
Client.java
package test;
import …*;
public class Client {
Note: evict() To detach the object from session cache, hibernate provides evict() method. After
detaching the object from the session, any change to object will not be persisted. The associated objects
will also be detached if the association is mapped with cascade="evict".
Auto DDL
And
show_sql
Auto DDL configuration is made in hibernate.cfg.xml.
<property name="hbm2ddl.auto">create</property>
<property name="hbm2ddl.auto">update</property>
<property name="hbm2ddl.auto">validate</property>
<property name="hbm2ddl.auto">create-drop</property>
• In case of create, create the schema, the data previously present (if there) in the schema is lost
• In case of update, if schema is not present in the DB then the schema is created.
• In case of validate, if schema does not exists in DB, it is not created. Instead, it will throw an
error:- Table not found:<table name>
• In case of create-drop, schema is not dropped on closing the session. It drops only on closing
the SessionFactory.
• In case if I give any value to this property(say abc, instead of above four values discussed
above) or it is just left blank. It shows following behaviour:
When we want to have all the queries fired by hibernate then we can use the following property:
<property name="show_sql">true</property>
Project Structure:
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver
</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe
</property>
<property name="connection.username">system</property>
<property name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property
name="connection.dialect">org.hibernate.dialect.OracleDialect
</property>
<property name="hbm2ddl.auto">create</property>
<!--
<property name="hbm2ddl.auto">update</property>
<property name="hbm2ddl.auto">validate</property>
<property name="hbm2ddl.auto">create-drop</property>
-->
<property name="show_sql">true</property>
<mapping resource="resources/student.hbm.xml"/>
<mapping resource="resources/course.hbm.xml"/>
<mapping resource="resources/employee.hbm.xml"/>
<mapping resource="resources/department.hbm.xml"/>
</session-factory>
</hibernate-configuration>
CRUD
CRUD : Create-Read-Update-Delete
Project Structure:
Student.java
package beans;
public class Student {
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String email, String address)
{
super();
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public Student() {
}
<mapping resource="resources/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Student" table="student" schema="system">
<id name="id"/>
<property name="name"/>
<property name="email"/>
<property name="address"/>
</class>
</hibernate-mapping>
Insertion.java
package test;
import …*;
t.commit();
System.out.println("id is : "+pk);
s.close();
sf.close();
}
Update.java
package test;
import …;
t.commit();
s.close();
sf.close();
}
UpdateVsMerge.java
package test;
import …;
s.merge(st);
/*
* or use
* 2. s.merge(st); but it will return nothing
* Limitations for the above methods:
1. pk cannot be updated
* 2. the whole row will be updated not specific column
* Note: in case of update() if session contains the same
object(persistent) then it will throw exception
*to overcome this we can go for merge();
*
* or use
* 3. s.saveOrUpdate(st) as mentioned in Insertion
*/
t.commit();
s.close();
sf.close();
}
Select.java
package test;
import …;
/*
* or use
* 2. s.load(Student.class,101);
* Note:
* in case of load() select operation is not performed at
load(Student.class,101)
* rather
*
*/
s.close();
sf.close();
Delete.java
package test;
import …;
t.commit();
s.close();
sf.close();
System.out.println("deletion successful");
}
Primary Key – Auto Generators
5. Hilo : db and application layer both are responsible. Application layer is responsible to store
next high value.
it will create one hibernate_hilo table to store next_high value.
At first deployment, next_hi=0. insertion order : 1,2,3,4,...
At second deployment, next_hi=1. insertion order : 32767,32768,32769,32770,...
At third deployment, next_hi=2. insertion order : 65535,65536,...
6. Native : (increment,identity,sequence). it works on increment. If db doesn't support this,
it opts for identity. If db doesn't support identity as well then it opts for sequence.
7. Foreign
8. Custom: =>sequence can be created in oracle as follows:
SQL> create sequence mysequence
start with 1000
increment by 1
nocycle
nocache;
=>Lec16 illustrates the above genertors using web project on Apache Tomcat Server.
Project Structure:
BookMyBus.java
public class BookMyBus {
private int id;
private String busName;
private String timeToBoard;
private String startFrom;
private int seatNumber;
public BookMyBus(int id, String busName, String timeToBoard,
String startFrom, int seatNumber) {
super();
this.id = id;
this.busName = busName;
this.timeToBoard = timeToBoard;
this.startFrom = startFrom;
this.seatNumber = seatNumber;
}
public BookMyBus() {
}
//Setters and Getters
}
bookMyBus.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.BookMyBus" table="ticketbook" schema="system">
<id name="id">
<!-- generator class="assigned"/-->
<!--generator class="identity"/-->
<generator class="sequence">
<param name="sequence">mysequence</param>
</generator>
</id>
<property name="busName"/>
<property name="timeToBoard"/>
<property name="startFrom"/>
<property name="seatNumber"/>
</class>
</hibernate-mapping>
mysql.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.jdbc.Driver
</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/test
</property>
<property name="connection.username">system</property>
<property name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property
name="connection.dialect">org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="resources/bookMyBus.hbm.xml"/>
</session-factory>
</hibernate-configuration>
oracle.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver
</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe
</property>
<property name="connection.username">system</property>
<property name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property
name="connection.dialect">org.hibernate.dialect.OracleDialect
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="resources/bookMyBus.hbm.xml"/>
</session-factory>
</hibernate-configuration>
SaveClient.java
package test;
import …;
}
HQL – Hibernate Query Language
Project Structure:
NewStudent.java
package beans;
Student.java
package beans;
public class Student {
private int id;
private String name;
private String email;
private int marks;
public Student() {
super();
}
public Student(int id, String name, String email, int marks) {
super();
this.id = id;
this.name = name;
this.email = email;
this.marks = marks;
}
//Setters and Getters
public String toString(){
return "[ID : "+id+", Name : "+name+", Email : "+email+",
Marks : "+marks+"]";
}
}
oracle.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver
</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe
</property>
<property name="connection.username">system</property>
<property name="connection.password">hussain</property>
<property name="connection.pool_size">10</property>
<property
name="connection.dialect">org.hibernate.dialect.OracleDialect
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="resources/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.OldStudent" table="oldstudent"
schema="system">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<property name="email"/>
<property name="marks"/>
</class>
</hibernate-mapping>
Save_Data.java
package test;
import …;
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();
OldStudent os1=
new OldStudent(-1,"name01","[email protected]",78);
OldStudent os2=
new OldStudent(-1,"name02","[email protected]",79);
OldStudent os3=
new OldStudent(-1,"name03","[email protected]",77);
OldStudent os4=
new OldStudent(-1,"name04","[email protected]",76);
OldStudent os5=
new OldStudent(-1,"name05","[email protected]",75);
s.save(os1);s.save(os2);s.save(os3);s.save(os4);s.save(os5);
s.save(s1);s.save(s2);s.save(s3);s.save(s4);s.save(s5);
t.commit();
s.close();
sf.close();
}
Insert_HQL.java
package test;
import …;
public class Insert_HQL {
public static void main(String[] args) {
Configuration cfg=new
Configuration().configure("resources/oracle.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();
String hql=
"insert into NewStudent(id,name,email,marks) select
s.id,s.name,s.email,s.marks from OldStudent s";
Query query=s.createQuery(hql);
int i=query.executeUpdate();
System.out.println(i+" rows effected");
s.close();
sf.close();
Update_HQL.java
package test;
import …;
public class Update_HQL {
public static void main(String[] args) {
Configuration cfg=new
Configuration().configure("resources/oracle.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();
String hql="update Student set email='[email protected]'
where id=2";
Query query=s.createQuery(hql);
int i=query.executeUpdate();
System.out.println(i+" rows effected");
s.close();
sf.close();
}
}
Delete_HQL.java
package test;
import …;
s.close();
sf.close();
}
Select_HQL.java
package test;
import …;