0% found this document useful (0 votes)
852 views

Hibernate by Naveen

The document discusses Hibernate programming basics including project structure, mapping files, configuration files, and object states. It describes a sample project structure with Student.java, student.hbm.xml, and hibernate.cfg.xml files. It explains the mapping between the Student class and database table using annotations in the mapping file. The configuration file defines database connection properties and references the mapping file. It also discusses setting hbm2ddl.auto to automatically generate the database schema. Finally, it summarizes the four states an object can have in Hibernate - transient, persistent, permanent, and detached - and provides an example demonstrating the state changes when interacting with the session and committing transactions

Uploaded by

waquar hussain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
852 views

Hibernate by Naveen

The document discusses Hibernate programming basics including project structure, mapping files, configuration files, and object states. It describes a sample project structure with Student.java, student.hbm.xml, and hibernate.cfg.xml files. It explains the mapping between the Student class and database table using annotations in the mapping file. The configuration file defines database connection properties and references the mapping file. It also discusses setting hbm2ddl.auto to automatically generate the database schema. Finally, it summarizes the four states an object can have in Hibernate - transient, persistent, permanent, and detached - and provides an example demonstrating the state changes when interacting with the session and committing transactions

Uploaded by

waquar hussain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Hibernate Programming

Basics
Project Structure:

Course.java //No Use

Department.java //No Use

Employee.java //No Use

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 -->

<!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" />
<!--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 -->

<!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.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:

public class ObjectStatesDemo {


public static void main(String[] args) {

// Transient object state


Student student = new Student();
student.setId(101);
student.setName("Mukesh");
student.setRoll("10");
student.setDegree("B.E");
student.setPhone("9999");
// Transient object state
Session session = new
AnnotationConfiguration().configure()
.buildSessionFactory().openSession();
Transaction t = session.beginTransaction();
// Persistent object state
session.save(student);
t.commit();
// Persistent object state
session.close();
// Detached object state

}
}
Asdf
Project Structure :

Students.java
package beans;

public class Student {


private int id;
private String name;
private String email;
private int marks;

public Student(int id, String name, String email, int


marks) {
super();
this.id = id;
this.name = name;
this.email = email;
this.marks = marks;
}
public Student() {
super();
}

//Setters and Getters


}
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="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 {

public static void main(String[] args) {


Student st=new
Student(111,"abc","[email protected]",500);
//Student object state is 'transient'

Configuration cfg=new Configuration();


cfg.configure("resources/hibernate.cfg.xml");
System.out.println("1");
SessionFactory sf=cfg.buildSessionFactory();
System.out.println("2");
Session s=sf.openSession();
System.out.println("3");
//Transaction t=s.beginTransaction();
System.out.println("4");
s.save(st);
System.out.println("5");
//student object state is 'persistent'
s.beginTransaction().commit();//object moved to db
System.out.println("6");
//student object state is 'permanent'
s.evict(st);
System.out.println("7");
//student object will be removed from 'persistent'
//then gc will collect student object
}
}

Note : Sql Queries:


1. create table student007(sid number primary key, sname varchar2(255), semail varchar2(255), smarks
number);

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:

-If schema is not present in the DB:- It creates the schema

-If schema is present in the DB:- update the schema.

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() {
}

//Setters and Getters


public String toString(){
return "ID => "+id+" : Name => "+name+" : Email => "+
email+" : Address => "+address;
}
}
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">create</property>
after running insertion change it to 'update' -->
<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.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 …*;

public class Insertion {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.hbm.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

Student st=new Student(101,"abc","[email protected]","res01");


int pk=(int) s.save(st);
/*
* or use
* 2. s.persist(st); but it will return nothing (note: save
can be used without txn
*boundaries but persist must be used within txn boundaries)
* or use
* 3. s.saveOrUpdate(st); will return nothing. it check
first if data with the id
*already exists or not. If yes, then update is performed
else
*insertion is performed
*/

t.commit();
System.out.println("id is : "+pk);
s.close();
sf.close();

}
Update.java
package test;

import …;

public class Update {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.hbm.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

Student st=new Student(101,"abc","[email protected]","res01");


//s.update(st);
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();

}
UpdateVsMerge.java
package test;

import …;

public class UpdateVsMerge {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.hbm.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

Student student=(Student)s.get(Student.class, 101);


System.out.println(student);
Student st=new Student(101,"xyz","[email protected]","res01");
System.out.println(st);
//s.update(st); // it will not work as object with the same
id is already contained in the session

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 …;

public class Select {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.hbm.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
//for select operation not txn boundary is required
Object o=(Object)s.get(Student.class,101);//if id doesn't
exist then it will return null
Student st=null;
if(o!=null){
st=(Student)o;//if o is null then 'NullPointerExcetion
is thrown'
System.out.println(st);
}
else
System.out.println("Record with the id doesn't
exist");

/*
* or use
* 2. s.load(Student.class,101);
* Note:
* in case of load() select operation is not performed at
load(Student.class,101)
* rather
*
*/

o=s.load(Student.class, 101);//select operation is not


performed here
st=(Student)o;
System.out.println(st.getId());//select operation is not
performed here; ObjectNotFoundException will be thrown if
record doesn't exist
System.out.println(st.getName());//select operation is
performed here; ObjectNotFoundException will be thrown if
record doesn't exist
System.out.println(st.getEmail());//select operation is
performed here; ObjectNotFoundException will be thrown if
record doesn't exist
System.out.println(st.getAddress());//select operation is
performed here; ObjectNotFoundException will be thrown if
record doesn't exist

s.close();
sf.close();

Delete.java
package test;

import …;

public class Delete {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.hbm.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

//Student st=new Student(101,"abc","[email protected]","res01");


//Student st=(Student)s.get(Student.class, 101);
Student st=new Student();
//any of the above object can be used.
st.setId(101);
System.out.println("Deleting "+st);
s.delete(st);//won't give any exception if record is not
found

t.commit();
s.close();
sf.close();
System.out.println("deletion successful");

}
Primary Key – Auto Generators

There following pk auto generators:

1. Assigned(default) : User is responsible to pass id


2. Increment : Application is responsible(it will select max id from the table and increment by 1)
there is chance to get error while inserting if multiple users acting on it at the same time
if it is not synchronized. In this case, two users may get the same id, one will be
entertained and other will get error.
3. Identity : db is responsible to generate id. oracle doesn't support this.
MySQL and DB2 have auto increment pk, so they support this.
Application will send only non pk to db.
4. Sequence : db and application layer both are responsible.
internally a sequence table(hibernate_sequence) is generated. every time
sequence.next is fetched and is taken as id.
by default starts with 1 and increment by 1.

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 …;

public class SaveClient {

public static void main(String[] args) {


Configuration cfg=new
Configuration().configure("resources/oracle.cfg.xml");
//Configuration cfg=new
Configuration().configure("resources/mysql.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction t=s.beginTransaction();

BookMyBus b=new BookMyBus(4,"Opolo","07-08-2019


10:30pm","ANVT",18);
s.save(b);
t.commit();
s.close();
sf.close();
}

}
HQL – Hibernate Query Language
Project Structure:

NewStudent.java
package beans;

public class NewStudent {


private int id;
private String name;
private String email;
private int marks;
public NewStudent() {
super();
}
public NewStudent(int id, String name, String email, int marks) {
super();
this.id = id;
this.name = name;
this.email = email;
this.marks = marks;
}
//Setters and Getters
}
OldStudent.java
package beans;

public class OldStudent {


private int id;
private String name;
private String email;
private int marks;
public OldStudent() {
super();
}
public OldStudent(int id, String name, String email, int marks) {
super();
this.id = id;
this.name = name;
this.email = email;
this.marks = marks;
}
//Setters and Getters

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>

<class name="beans.NewStudent" table="newstudent"


schema="system">
<id name="id"/>
<property name="name"/>
<property name="email"/>
<property name="marks"/>
</class>

<class name="beans.Student" table="student" schema="system">


<id name="id"/>
<property name="name"/>
<property name="email"/>
<property name="marks"/>
</class>

</hibernate-mapping>
Save_Data.java
package test;

import …;

public class Save_Data {

public static void main(String[] args) {


Configuration cfg=new Configuration();
cfg.configure("resources/oracle.cfg.xml");

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);

Student s1=new Student(-1,"name01","[email protected]",78);


Student s2=new Student(-1,"name02","[email protected]",79);
Student s3=new Student(-1,"name03","[email protected]",77);
Student s4=new Student(-1,"name04","[email protected]",76);
Student s5=new Student(-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 …;

public class Delete_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="delete Student where id=2";
Query query=s.createQuery(hql);
int i=query.executeUpdate();
System.out.println(i+" rows effected");

s.close();
sf.close();
}

Select_HQL.java
package test;

import …;

public class Select_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();

//selecting one attribute of an object


String hql1="select name from Student where id=1";
Query query=s.createQuery(hql1);
String name=(String) query.uniqueResult();
System.out.println(name);
//selecting one Student object
String hql2="from Student where id=1";
Query query2=s.createQuery(hql2);
Student student=(Student) query2.uniqueResult();
System.out.println(student);

//selecting one column


String hql3="select email from Student";
Query query3=s.createQuery(hql3);
List<String> names=query3.list();
for(String n:names){
System.out.println(name);
}

//selecting multiple columns


String hql4="select name,email from Student";
Query query4=s.createQuery(hql4);
List<Object> list=query4.list();
for(Object o:list){
Object rec[]=(Object[])o;
System.out.println("Name : "+rec[0]+", Email :
"+rec[1]);
}

//selecting multiple student objects


String hql5="from Student";
Query query5=s.createQuery(hql5);
List<Student> students=query5.list();
for(Object st:students){
System.out.println(st);
}
s.close();
sf.close();

You might also like