Nearby lessons

13 of 19

Hibernate - Connection Pooling (Proxool, JNDI)

📌 What You Will Learn
  • Understand Hibernate - Connection Pooling (Proxool, JNDI)
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Connection Pooling (Proxool, JNDI) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Connection Pooling (Proxool, JNDI) — hibernate.cfg.xml

  • import javax.persistence.Table;
  • import javax.persistence.TableGenerator;
  • import org.hibernate.annotations.Generated;
  • import org.hibernate.annotations.GenericGenerator;
  • import org.hibernate.annotations.Parameter;
  • @Entity
  • @Table(name="emp1")
  • public class Employee {
  • @Id
  • @Column(name="ENO")
  • @SequenceGenerator(name="seqGen", sequenceName="my_sequence")
  • @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seqGen")
  • //@GeneratedValue(strategy=GenerationType.IDENTITY)
  • //@GeneratedValue(strategy=GenerationType.AUTO)
  • @TableGenerator(name="tableGen", table="my_table", pkColumnName="id", pkColumn

Value="10", valueColumnName="next_hi")

  • @GeneratedValue(strategy=GenerationType.TABLE, generator="tableGen")
  • @GenericGenerator(name="incrementGen", strategy="increment")
  • @GeneratedValue(generator="incrementGen")
  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • public int getEno() {
  • return eno;
  • public void setEno(int eno) {
  • this.eno = eno;
  • public String getEname() {
  • return ename;
  • public void setEname(String ename) {
  • this.ename = ename;
  • public float getEsal() {
  • return esal;
  • public void setEsal(float esal) {
  • this.esal = esal;
  • public String getEaddr() {
  • return eaddr;
  • public void setEaddr(String eaddr) {
  • this.eaddr = eaddr;
Example01
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7 
8<session-factory>
9 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
10 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
11<property name="connection.username">system</property>
12<property name="connection.password">durga</property>
13<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
14<property name="show_sql">true</property>
15<mapping class="com.durgasoft.hbn.pojo.Employee"/>
16</session-factory>
17 
18<!--
19<session-factory>
20<property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
21<property name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
22<property name="connection.username">root</property>
23<property name="connection.password">root</property>
24<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
25<property name="show_sql">true</property>
26<mapping class="com.durgasoft.hbn.pojo.Employee"/>
27</session-factory>
28-->
29</hibernate-configuration>
30

Connection Pooling (Proxool, JNDI) — ClientApp.java

Example02
JCode Cell
1 
2package com.durgasoft.hbn.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.hbn.pojo.Employee;
12 
13public class Test {
14 
15public static void main(String[] args)throws Exception {
16Configuration cfg = new Configuration();
17cfg.configure();
18StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
19builder = builder.applySettings(cfg.getProperties());
20StandardServiceRegistry registry = builder.build();
21SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
22Session session = sessionFactory.openSession();
23Employee emp = new Employee();
24//emp.setEno(111);
25emp.setEname("AAA");
26emp.setEsal(5000);
27emp.setEaddr("Hyd");
28Transaction tx = session.beginTransaction();
29session.save(emp);
30tx.commit();
31System.out.println("Employee Inserted Successfully");
32 
33}
34}
35

Transaction Management

Transaction is a unit of work performed by Front End applications on Back End System.

EX: Deposit some amount in an Account. Withdraw some amount from an Account Transfer some amount from one account to another account.

IN database applications, Every Transaction must follow ACID properties

  • Atomicity: This property will make the Transaction either in SUCCESS state or in FAILURE state.

In Database related applications, if we perform all operations then the Transaction is available in SUCCESS State, if we perform none of the operations then the Transaction is available in FAILURE state.

  • Consistency: In database applications, Before the Transaction and After the Transaction Database state must be in stable.
  • Isolation: If we run more than one Transaction on a single Data item then that Transactions are called as "Concurret Transactions". In Transactions Concurrency , one transaction execution must not give effect to another Transaction, this rule is called as "Isolation" property.
  • Durability: After committing the Transaction, if any failures are coming like Power failure, OS failure,...after getting the System if we open the transaction then the modifications which we performed during the transaction must be preserved.

In JDBC, to perform Automicity property we have to change Connections auto-commit nature and we have to perform either commit() or rollback() at the end of Transaction.

Example03
JCode Cell
1 
2Connection con = DriverManager.getConnection(---);
3con.setAutoCommit(false);
4try{
5---instructions-----
6con.commit();
7}catch(Exception e){
8e.printStacktrace();
9con.rollback();
10}
11

Transaction Management — Employee.java

In Hibernate applications, if we want to manage Transactions Automicity property then we have to use the following steps.

  • Declare Transaction Before try.
  • Create Transaction object inside try block.
  • Perform commit() operation at end of Transaction.
  • Perform rollback() operation at catch block.

Transaction tx = null; try{ ----- tx = session.beginTransaction(); ---- ----- tx.commit(); }catch(Exception e){ tx.rollback(); }

Example:

Example04
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="account")
11public class Account {
12@Id
13@Column(name="ACCNo")
14private String accNo;
15@Column(name="BALANCE")
16private int balance;
17 
18public String getAccNo() {
19return accNo;
20}
21public void setAccNo(String accNo) {
22this.accNo = accNo;
23}
24public int getBalance() {
25return balance;
26}
27public void setBalance(int balance) {
28this.balance = balance;
29}
30 
31 
32}
33

Transaction Management — oracle_cfg.xml

Example05
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.username">system</property>
11<property name="connection.password">durga</property>
12<property name="show_sql">true</property>
13<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
14<mapping class="com.durgasoft.pojo.Account"/>
15</session-factory>
16</hibernate-configuration>
17

Transaction Management — mysql_cfg.xml

Example06
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
9 <property name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
10 <property name="connection.username">root</property>
11<property name="connection.password">root</property>
12<property name="show_sql">true</property>
13<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
14<mapping class="com.durgasoft.pojo.Account"/>
15</session-factory>
16</hibernate-configuration>
17

Transaction Management — Test.java

Example07
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.pojo.Account;
12 
13public class Test {
14 
15public static void main(String[] args) {
16Configuration oracle_Cfg = null;
17Configuration mysql_Cfg = null;
18SessionFactory oracle_Sf = null;
19SessionFactory mysql_Sf = null;
20Session oracle_Session = null;
21Session mysql_Session = null;
22Transaction oracle_Tx = null;
23Transaction mysql_Tx = null;
24try {
25 oracle_Cfg = new Configuration();
26 oracle_Cfg.configure("oracle_cfg.xml");
27 mysql_Cfg = new Configuration();
28 mysql_Cfg.configure("mysql_cfg.xml");
29 
30 StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
31 builder = builder.applySettings(oracle_Cfg.getProperties());
32 StandardServiceRegistry oracle_registry = builder.build();
33 oracle_Sf = oracle_Cfg.buildSessionFactory(oracle_registry);
34 
35 builder = builder.applySettings(mysql_Cfg.getProperties());
36 StandardServiceRegistry mysql_registry = builder.build();
37 mysql_Sf = mysql_Cfg.buildSessionFactory(mysql_registry);
38 
39 oracle_Session = oracle_Sf.openSession();
40 mysql_Session = mysql_Sf.openSession();
41 
42 Account source_Account = (Account)oracle_Session.get("com.durgasoft.pojo.Account", "abc123");
43 int source_Balance = 0;
44 source_Balance = source_Account.getBalance();
45 source_Balance = source_Balance - 5000;
46 source_Account.setBalance(source_Balance);
47 
48 Account target_Account = (Account)mysql_Session.get("com.durgasoft.pojo.Account", "xyz123");
49 int target_Balance = 0;
50 target_Balance = target_Account.getBalance();
51 target_Balance = target_Balance + 5000;
52 target_Account.setBalance(target_Balance);
53 
54 
55 oracle_Tx = oracle_Session.beginTransaction();
56 mysql_Tx = mysql_Session.beginTransaction();
57 oracle_Session.update(source_Account);
58 mysql_Session.update(target_Account);
59 oracle_Tx.commit();
60 mysql_Tx.commit();
61 System.out.println("5000Rs Transfered from "+source_Account.getAccNo()+" to "+target_Account.getAccNo());
62 System.out.println("Transaction SUCCESS");
63} catch (Exception e) {
64 e.printStackTrace();
65 oracle_Tx.rollback();
66 mysql_Tx.rollback();
67 System.out.println("Transaction Failure");
68}finally {
69 oracle_Session.close();
70 mysql_Session.close();
71 oracle_Sf.close();
72 mysql_Sf.close();
73}
74}
75}
76

Transaction Management

If we execute more than one transaction on a single data item then that transactions are called as Concurrent Transactions.

In Transactions concurrency we are able to get the following data consistency problems while executing more than one transaction at a time.

  • Lost Update Problem
  • Dirty Read Problem
  • Non Repeatable Read Problem
  • Phanthom Read Problem

Lost Update Problem

In Transactions concurrency, if one transaction perform updations over the data with out commit operation , mean while, other transactions perform updations with commit operation then the first transaction updations are lost, this data consistency problem is called as Lost Update problem.

Dirty Read Problem

In Transactions concurrency, if one transaction perform updations over data with out performing commit / rollback, mean while if other Transaction perform Read operation over the uncommitted data with out performing commit/rollback operations, in this context, if first transaction perform Rollback operation then the read operation performed by second transaction is Dirty Read, this problem is called as Dirty Read problem.

Non Repeatable Read Problem

In Transactions concurrency, One transaction perform continous read operations to get same results, mean while, between two read operations another transaction performs update operation over the same data, in this context, in the next read operation performed by first transaction may not get same repeatable results, this problem is called as Non Repeatable Read Problem.

Phanthom Read Problem

In Transactions concurrency, one transaction perform read operation continously to get same no of results at each and every read operation , mean while, other transactions may perform insert operations between two read operations performed by first transactions, in this context, in the next read operation performed by first transaction may not generate the same no of results, this problem is called as "Panthom Read" Problem, here the extra records inserted by second transaction are called as "Panthom Records".

  • public sttaic final int TRANSCATION_NONE = 0;
  • public sttaic final int TRANSCATION_READ_UNCOMMITTED = 1;
  • public sttaic final int TRANSCATION_READ_COMMITTED = 2;
  • public sttaic final int TRANSCATION_REPETABLE_READ = 4;
  • public sttaic final int TRANSCATION_SERIALIZABLE = 8;

public void setTransactionIsolation(int isolation_Level)

EX: con.setTransactionIsolation(Connection.TRANSACTION_READ_ COMMITTED);

<property name="hibernate.connection.isolation>val</property>

Where value may be either of the following Constants

NONE = 0; READ_UNCOMMITTED = 1; READ_COMMITTED = 2; REPEATABLE_READ = 4; SERIALIZABLE = 8;

Example12
JCode Cell
1 
2<hibernate-configuration>
3<session-factory>
4----
5<property name="hibernate.connection.isolation>
6 SERIALIZABLE
7</property>
8-----
9</session-factory>
10</hibernate-configuration>
11

Connection Pooling in Hibernate

In general, in Database related applications, if we want to perform database operations first we have to create connection object before database operations then we have to destroy connection object after the database operations. If we use this approach in database related applications then application performance will be reduced, because, Creating connection object and destroying Connection objects are two expensive processes.

In the above context, to improve application performance we have to avoid Connection object creation and Destruction processes every time, for this, we have to use Connection Pooling.

In Connection Pooling, first, we will create a pool object with a set of Connection objects at application loading time , then, we get Connection object from Pool when we want to perform database operations, after the database operations we will send Connection object back to Pool object with out destroying Connection object.

To provide Connection pooling in JDBC applications we have to use the following steps.

Create DataSource object

DataSource is an object , it able to manage all JDBC parameters inorder to create Connection objects and it able to manage Pool objects with Connection objects.

In JDBC, to represent DataSource object, JDBC has provided a predefined interface in the form of javax.sql.DataSource and its implementationa are provided by database vendors.

EX1: OracleDataSource provided by Oracle. EX2: MySQLDataSource provided my MySQL. EX: OracleDataSource ds = new OracleDataSource();

Set JDBC Parameters to create Connection objects in POOL

In DataSource, to create Connection objects in POOL , we have to provide Driver URL, Database User Name and Database password,....., for this, we have to use the following methods.

public void setURL(String driver_URL) public void setUser(String db_User_Name) public void setPassword(String password)

EX:

ds.setURL("jdbc:oracle:thin:@localhost:1521:xe"); ds.setUser("system"); ds.setPassword("durga");

Get Connection Object from DataSource

To get Connection object from DataSource we have to use the following method. public Connection getConnection()

EX: Connection con = ds.getConnection();

Note:Perform Database operations with the Connection object

Close Connection object

public void close()

EX: con.close();

Note: When we access close() on Connection object which we get from Pool , then, Connection object will not be destroyed, whene Connection object will be send back to Pool object.

Example17
JCode Cell
1 
2package com.durgasoft.jdbc;
3 
4import java.sql.Connection;
5import java.sql.ResultSet;
6import java.sql.Statement;
7 
8import oracle.jdbc.pool.OracleDataSource;
9 
10public class ConnectionPoolingEx {
11public static void main(String[] args) throws Exception {
12OracleDataSource ds = new OracleDataSource();
13ds.setURL("jdbc:oracle:thin:@localhost:1521:xe");
14ds.setUser("system");
15ds.setPassword("durga");
16Connection con = ds.getConnection();
17Statement st = con.createStatement();
18ResultSet rs = st.executeQuery("select * from emp1");
19System.out.println("ENO\tENAME\tESAL\tEADDR");
20System.out.println("-------------------------------");
21while(rs.next()) {
22System.out.println(rs.getInt(1)+"\t"+rs.getStrin(2)+"\t"+ rs.getFloat(3)+"\t"+rs.getString(4));
23}
24con.close();
25}
26}
27

Close Connection object

In Hibernate applications, there are three ways to implement Connection Pooling.

  • Default Connection Pooling Mech in Hibernate
  • Third Party Vendors provided Connection pooling Mechs
  • Application Servers provided Connection pooling Mechs

Default Connection Pooling Mech in Hibernate

In Hibernate applications, to interact with databases hibernate software is generating Connection objects by using its built-in Connection pooling mechanism .

Hibernate Software has implemented its built-in connection pooling mechanism in the form of a predefined class like

org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl

Hibernate provided built-in Connection pooling mechanism is able to allow 20 Connections as max count and 1 connection as min count, we can modify this pool size in hibernate applications as per the requirement by using "connection.pool_size" property in hibernate configuration file.

  • <hibernate-configuration>
  • <session-factory>
  • <property name="connection.pool_size">10</property>
  • </session-factory>
  • </hibernate-configuration>

Note: Hibernate Software provided built-in connection pooling mechanism is suggestible upto Development and Testing phases, it is not suggestible for Production mode of our project.

Third Party Vendors provided Connection pooling Mechs

In general, in database related applications we will use the following three third party vendors provided connection pooling mechanisms.

  • DBCP
  • C3P0
  • Proxool

Note: Hibernate is not providing support for DBCP Connection pooling mechanism, but, Hibernate has provided predefined support for C3P0 and Proxool connection pooling mechanisms.

C3P0 Connection Pooling Mechanism In Hibernate

If we want to use C3P0 Connection pooling mechanism in hibernate applications then we have to declare the following properties in hibernate configuration file.

hibernate.connection.provider_class

This property will take Connection Pooling provider class which was provided by hibernate software for C3P0 connection pooling mechanism in the form of "org.hibernate.c3p0.internal.C3P0ConnectionProvider".

Note: C3P0ConnectionProvider class will activate C3P0 connection pooling mechanism in Hibernate applications.

hibernate.c3p0.min_size

It will take an int value which is representing minimum no of Connection objects in a pool.

hibernate.c3p0.max_size

It will take int value which is representing maximum no of Connection objects in a pool.

hibernate.c3p0.timeout

It will take connections idle time to destroy.

hibernate.c3p0.max_statements — Employee.java

It will take an int value representing no of statements max for Connection objects. EX: hibernate.cfg.xml

  • <hibernate-configuration>
  • <session-factory>
  • <property name="connection.pool_size">10</property>
  • </session-factory>
  • </hibernate-configuration>
  • <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">durga</property>
  • <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  • <property name="show_sql">true</property>
  • <!-- C3P0 Connection Pooling Properties -->
  • <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0

ConnectionProvider</property>

  • <property name="hibernate.c3p0.min_size">1</property>
  • <property name="hibernate.c3p0.max_size">19</property>
  • <property name="hibernate.c3p0.timeout">120</property>
  • <property name="hibernate.c3p0.max_statements">10</property>
  • <mapping class="com.durgasoft.pojo.Employee"/>
  • </session-factory>
  • </hibernate-configuration>

Note: Add the following jars to the Hibernate Library.

  • c3p0-0.9.2.1.jar
  • hibernate-c3p0-4.3.11.Final.jar
  • mchange-commons-java-0.2.3.4.jar

Example:

Example26
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47}
48

hibernate.c3p0.max_statements — hibernate.cfg.xml

Example27
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.username">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_sql">true</property>
14<!-- <property name="connection.pool_size">10</property> -->
15<!-- C3P0 Connection Pooling Properties -->
16<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
17<property name="hibernate.c3p0.min_size">1</property>
18<property name="hibernate.c3p0.max_size">19</property>
19<property name="hibernate.c3p0.timeout">120</property>
20<property name="hibernate.c3p0.max_statements">10</property>
21 
22<mapping class="com.durgasoft.pojo.Employee"/>
23</session-factory>
24 
25</hibernate-configuration>
26

hibernate.c3p0.max_statements — Test.java

Example28
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.pojo.Employee;
12 
13public class Test {
14 
15public static void main(String[] args) {
16Transaction tx = null;
17SessionFactory sessionFactory = null;
18Session session = null;
19try {
20 Configuration config = new Configuration();
21 config.configure("hibernate.cfg.xml");
22 StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
23 builder = builder.applySettings(config.getProperties());
24 StandardServiceRegistry registry = builder.build();
25 sessionFactory = config.buildSessionFactory(registry);
26 session = sessionFactory.openSession();
27 Employee emp = new Employee();
28 emp.setEno(333);
29 emp.setEname("CCC");
30 emp.setEsal(7000);
31 emp.setEaddr("Hyd");
32 tx = session.beginTransaction();
33 session.save(emp);
34 tx.commit();
35 System.out.println("Employee Inserted Successfully");
36} catch (Exception e) {
37 e.printStackTrace();
38 tx.rollback();
39 System.out.println("Employee Insertion Failure");
40}finally {
41 session.close();
42 sessionFactory.close();
43}
44}
45}
46

Proxool Connection Pooling Mechanism — proxool.xml

If we want to use Proxool Connection Pooling mechanism in hibernate appliocations then we have to use the follolwing steps.

  • Provide Proxool connection pooling mechanism configurations in an xml file called as proxool configuration file.
  • Configure proxool configuration file in hibernate configuration file.
  • proxool configuration file:

It is an xml file, it includes all configuration details of proxool connection pooling mechanism which includes driver class name, driver url, database user name, datyabase password, minimum connection count, maximum connection count,......

To provide the above configuration details we have to use the following xml tags.

  • <proxool-config>
  • <proxool>
  • <alias>proxool_alias_name</alias>
  • <driver-class> driuver class name</driver-class>
  • <driver-url> driver url </driver-url>
  • <driver-properties>
  • <property name="prop_name" value="prop_value">
  • </driver-properties>
  • <minimum-connection-count> min_size </minimum-connection-count>
  • <maximum-connection-count> max_size </maximum-connection-count>
  • </proxool>
  • </proxool-config>

EX:

Example29
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<proxool-config>
4<proxool>
5<alias>proxool</alias>
6<driver-class>oracle.jdbc.OracleDriver</driver-class>
7<driver-url>jdbc:oracle:thin:@localhost:1521:xe</driver-url>
8<driver-properties>
9<property name="user" value="system"></property>
10<property name="password" value="durga"></property>
11</driver-properties>
12<minimum-connection-count>10</minimum-connection-count>
13<maximum-connection-count>20</maximum-connection-count>
14</proxool>
15</proxool-config>
16

Proxool Connection Pooling Mechanism — hibernate.cfg.xml

To configure proxool configuration file in hibernate configuration file we have to use the following tags along with dialect and mapping configurations

  • hibernate.connection.provider_class: It will take Proxool connection pooling provider class which was provided by hibernate software in the form of "org.hibernate.connection.ProxoolConnectionProvider" inorder to activate proxool connection pooling mechanism.
  • hibernate.proxool.pool_alias: It will take proxool alias name which we defined in proxool configuration file.
  • hibernate.proxool.xml: It will take the name and location of proxool configuration file.

EX:

Example30
JCode Cell
1 
2<hibernate-configuration>
3<session-factory>
4<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect </property>
5<property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
6<property name="hibernate.proxool.pool_alias">proxool</property>
7<property name="hibernate.proxool.xml">proxool.xml</property>
8<mapping class="com.durgasoft.hbn.pojo.Employee"/>
9</session-factory>
10</hibernate-configuration>
11

Proxool Connection Pooling Mechanism — Employee.java

Note: To use this mechanism, we have to add the following JAR files in Hibernate Library.

  • proxool-0.8.3.jar
  • hibernate-proxool-4.3.11.Final.jar

EXample:

Example31
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47}
48

Proxool Connection Pooling Mechanism — hibernate.cfg.xml

Example32
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
9<property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
10<property name="hibernate.proxool.pool_alias">proxool</property>
11<property name="hibernate.proxool.xml">proxool.xml</property>
12<mapping class="com.durgasoft.pojo.Employee"/>
13</session-factory>
14</hibernate-configuration>
15

Proxool Connection Pooling Mechanism — proxool.xml

Example33
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<proxool-config>
4<proxool>
5<alias>proxool</alias>
6<driver-class>oracle.jdbc.OracleDriver</driver-class>
7<driver-url>jdbc:oracle:thin:@localhost:1521:xe</driver-url>
8<driver-properties>
9<property name="user" value="system"></property>
10<property name="password" value="durga"></property>
11</driver-properties>
12<minimum-connection-count>10</minimum-connection-count>
13<maximum-connection-count>20</maximum-connection-count>
14</proxool>
15</proxool-config>
16

Proxool Connection Pooling Mechanism — Test.java

Example34
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.pojo.Employee;
12 
13public class Test {
14 
15public static void main(String[] args) {
16Transaction tx = null;
17SessionFactory sessionFactory = null;
18Session session = null;
19try {
20 Configuration config = new Configuration();
21 config.configure("hibernate.cfg.xml");
22 StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
23 builder = builder.applySettings(config.getProperties());
24 StandardServiceRegistry registry = builder.build();
25 sessionFactory = config.buildSessionFactory(registry);
26 session = sessionFactory.openSession();
27 Employee emp = new Employee();
28 emp.setEno(111);
29 emp.setEname("AAA");
30 emp.setEsal(5000);
31 emp.setEaddr("Hyd");
32 tx = session.beginTransaction();
33 session.save(emp);
34 tx.commit();
35 System.out.println("Employee Inserted Successfully");
36} catch (Exception e) {
37 e.printStackTrace();
38 tx.rollback();
39 System.out.println("Employee Insertion Failure");
40}finally {
41 session.close();
42 sessionFactory.close();
43}
44}
45}
46

Connection Pooling through Application Servers

  • Connection Pooling through Application Servers built in mechanisms by using JNDI:

JNDI [Java Naming And Directory Interface]: JNDI is a Middleware Service or an abstraction provided by SUN Micreosystems as part of J2EE and which is implemented by all the Application Servers vendors like Weblogic, JBOSS, Glassfish,.....

JNDI is existed inside the application Servers to provide any resource with Global Scope, that is, JNDI will share any resource like "DataSource" to all the applications which are running in the present application server.

In general, almost all the Application Servers are having their own Connection Pooling mechanisms, if we want to use Application Servers provided Connection pooling mechanisms we have to use the following steps.

1) Install Application Server. 2) COnfigure Connection Pooling and Datasource in JNDI provided by Application Servers. 3) Access Application Servers provided Datasource in our Application.

1) Install Application Server[Weblogic Server]

  • Download fmw_12.2.1.3.0_wls_quick.jar from internet[oracle.com]
  • Open command prompt in Administrator mode.
  • Set JAVA8 or JAVA7 in path.

set path=C:\Java\jdk1.8.0_144\bin;

  • Goto setup file loaction and execute JAR file with the following command.

F:\softwares\servers\weblogic>java -jar fmw_12.2.1.3.0_wls_quick.jar

  • Click on "Next" button.
  • Click on "Next" Button
  • Specify Home directory "Oracle"
  • Click on "Next" button.
  • Click on "Next" button.
  • Click on "Next" button
  • Click on "Install" button.
  • Click on "Next" button.
  • Click on "Finish" button.
  • Provide domain name "durga_domain".
  • Click on "Next" button.
  • Click on "Next" button.
  • Provide user name and password.

user name: weblogic password: weblogic_weblogic confirm password: weblogic_weblogic

  • Click on "Next" button.
  • Click on "Next" button.
  • Select "Adminstration Server"
  • CLick on "Next" button.
  • Click on "Next" button.
  • Click on "Create" button.
  • Click on "Next" button.
  • Click on "Finish" button.

Configure Connection Pooling and Datasource in JNDI provided by Application Servers

  • Goto durga_domain location

C:\Oracle\user_projects\domains\durga_domain

  • double click on "startWeblogic" batch file.
  • Open Browser and provide the following url to open Administration console.

http://localhost:7001/console

  • Provide domain user name and password.

user name: weblogic password: weblogic_weblogic

  • Click on "Login" button.
  • Go for Domain Structer and select "Services".
  • Select "DataSource".
  • Click on "New" button.
  • Select "Generic datasource".
  • Provide the following details.

Name: durgads Scope: GLOBAL JNDI Name: durgajndi Database Type: Oracle

  • Click on "Next" button.
  • Click on "Next" button.
  • Click on "Next" button.
  • Provide the following details.

Database Name: xe Host Name: localhost Port : 1521 Database User Name: system password: durga confirm password: durga

  • Click on "Next" button.
  • Click on "Next" button.
  • Select "admin server".
  • Click on "Finish" button.

If we want to get DataSource object from Weblogic Server provided JNDI into JDBC Application then we ahve to use the following steps.

  • Create Hashtable object and put the following Weblogic Server provided JNDI configurations:
  • INITIAL_CONTEXT_FACTORY: It is a context from javax.naming.Context class , it will take Server provided ContextFactory. Weblogic Server has provided a seperate ContextFactory in the form of weblogic.jndi.ELInitialContextFactory.
  • PROVIDER_URL: It is a constant provided by javax.naming.Context class, it will take JNDI server URL provided by Application Servers inorder to get Datasource object. Web logic Server has provided JNDI url like "t3://localhost:7001"
Example36
JCode Cell
1 
2 Hashtable<String, String> ht = new Hashtable<String, String>();
3 ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
4 
5

Create InitialContext object

javax.naming.InitialContext class is representing JNDI server or registry, it can be used to keep

resources in JNDI Server and retrive resources from JNDI server. To create InitialContext object we have to use the following constructor.

public InitialContext(Map map) EX: InitialContext context = new InitialContext(ht);

  • Get DataSource object from JNDI on the basis of JNDI Name which we configured in Appl

Server

To get DataSource object from weblogic application Server we have to use the following method.

public static Object lookup(String jndi_Name)

EX: DataSource ds = (DataSource)Context.lookup("durgajndi");

Get Connection from DataSource

To get Connection from dataSource we have to use the following method.

public Connection getConnection()

EX: Connection con = ds.getConnection();

Note: After getting Connection object we will provide our own JDBC Application logic inorder to perform Database operations.

EX:

JDBC Application to use Weblogic Server privided Connection pooling Mechanism through JNDI.

  • package com.durgasoft.jdbc;
  • import java.sql.Connection;
  • import java.sql.ResultSet;
  • import java.sql.Statement;
  • import java.util.Hashtable;
  • import javax.naming.Context;
  • import javax.naming.InitialContext;
  • import javax.sql.DataSource;
  • public class JdbcApp {
  • public static void main(String[] args)throws Exception {
  • Hashtable<String, String> ht = new Hashtable<String, String>();
  • ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory
  • ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
  • InitialContext context = new InitialContext(ht);
  • DataSource ds = (DataSource)context.lookup("durgajndi");
  • Connection con = ds.getConnection();
  • Statement st = con.createStatement();
  • ResultSet rs = st.executeQuery("select * from emp1");
  • System.out.println("ENO\tENAME\tESAL\tEADDR");
  • System.out.println("------------------------------");
  • while(rs.next()) {
  • System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getFloat(3)+"\t"+rs.getStri

ng(4));

Note: To run this example We have to keep ojdbc6.jar and weblogic.jar in build path. weblogic.jar is existed in weblogic server

C:\Oracle\wlserver\server\lib\weblogic.jar

If we want to use Application Server provided DataSource object in Hibernate applications then we have to provide the following properties configuration in hibernate configuration File.

hibernate.connection.provider_class

In Hibernate, Every Connection Pooling mechanism will have a seperate Provider Class, this property will take the Connection pooling mechanisms provider class which we defined by hibernate. For Application Servers Connection Pooling mechanisms we have to provide "org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl".

hibernate.connection.datasource

This property will take JNDI name of the datasource object which we configured in application Server.

hibernate.jndi.class

It will take ConnectionFactory class provided by application Servers. Weblogic server will use "weblogic.jndi.WLInitialContextFactrory" as value to this property.

hibernate.jndi.url

This property will take JNDI url to get DataSource object , All application Servers has to provide a seperate URL to access JNDI registry, Weblogic has provided "t3://localhost:7001" as JNDI url.

Example43
JCode Cell
1 
2<hibernate-configuration>
3<session-factory>
4<property ame="hibernate.connection.provider_class"> org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl
5</property>
6<property name="hibernate.connection.datasource">oraclejndi</property>
7<property name="hibernate.jndi.class">weblogic.jndi.WLInitialContextFactory</property>
8<property name="hibernate.jndi.url">t3://localhost:7001</property>
9<mapping class="com.durgasoft.pojo.Employee"/>
10</session-factory>
11</hibernate-configuration>
12

hibernate.jndi.url — Employee.java

Note: To run this example we have to keep weblogic.jar in Hibernate Lib and we must remove ojdbc6.jar from Hibernate Lib.

Example:

Example44
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3import javax.persistence.Column;
4import javax.persistence.Entity;
5import javax.persistence.Id;
6 
7@Entity
8@Table(name="emp1")
9public class Employee {
10@Id
11@Column(name="ENO")
12private int eno;
13@Column(name="ENAME")
14private String ename;
15@Column(name="ESAL")
16private float esal;
17@Column(name="EADDR")
18private String eaddr;
19 
20public int getEno() {
21return eno;
22}
23public void setEno(int eno) {
24this.eno = eno;
25}
26public String getEname() {
27return ename;
28}
29public void setEname(String ename) {
30this.ename = ename;
31}
32public float getEsal() {
33return esal;
34}
35public void setEsal(float esal) {
36this.esal = esal;
37}
38public String getEaddr() {
39return eaddr;
40}
41public void setEaddr(String eaddr) {
42this.eaddr = eaddr;
43}
44 
45 
46}
47

hibernate.jndi.url — hibernate.cfg.xml

Example45
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8<property name="hibernate.connection.provider_class">org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl</property>
9 <property name="hibernate.connection.datasource">oraclejndi</property>
10 <property name="hibernate.jndi.class">weblogic.jndi.WLInitialContextFactory</property>
11<property name="hibernate.jndi.url">t3://localhost:7001</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<mapping class="com.durgasoft.hbn.pojo.Employee"/>
14 
15</session-factory>
16 
17 
18</hibernate-configuration>
19

hibernate.jndi.url — Test.java

Example46
JCode Cell
1 
2package com.durgasoft.hbn.test;
3 
4import java.util.Properties;
5 
6import javax.naming.Context;
7import javax.naming.InitialContext;
8 
9import org.hibernate.Session;
10import org.hibernate.SessionFactory;
11import org.hibernate.Transaction;
12import org.hibernate.boot.registry.StandardServiceRegistry;
13import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
14import org.hibernate.cfg.Configuration;
15 
16import com.durgasoft.hbn.pojo.Employee;
17 
18public class Test {
19 
20public static void main(String[] args)throws Exception {
21 
22Configuration cfg = new Configuration();
23cfg.configure();
24StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
25builder = builder.applySettings(cfg.getProperties());
26StandardServiceRegistry registry = builder.build();
27SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
28Session session = sessionFactory.openSession();
29 
30Employee emp = new Employee();
31emp.setEno(111);
32emp.setEname("AAA");
33emp.setEsal(5000);
34emp.setEaddr("Hyd");
35Transaction tx = session.beginTransaction();
36session.save(emp);
37tx.commit();
38System.out.println("Employee Saved Successfully");
39}
40}
41

Bulk Operations

In General, in Hibernate Applications, by using org.hibernate.Session interface provided methods like save (), update (), saveOrUpdate (), delete (), get () ... we are able to perform manipulations over single record.

In Hibernate applications, if we want to perform manipulations over multiple records then we must use the following features provided by Hibernate.

  • HQL[Hibernate Query Language]
  • Native SQL
  • Criteria API

HQL [Hibernate Query Language]

HQL is a pwerfull query language provided by Hibernate inorder to perform manipulations over multiple records. HQL is an object oriented query language, it able to support for the object oriented features like encapsulation, polymorphism,.... , but, SQL is structered query language. HQL is database independent query language, but, SQL is database dependent query language. In case of HQL, we will prepare queries by using POJO class names and their properties, but, in case of SQL , we will prepare queries on the basis of database table names and table columns. HQL queries are prepare by using the syntaxes which are similar to SQL queries syntaxes. HQL is mainly for retrival operations , but, right from Hibernate3.x version we can use HQL to perform insert , update and delete operations along with select operations, but, SQL is able to allow any type of database operation. In case of JDBC, in case of SQL, if we execute select sql query then records are retrived from database table and these records are stored in the form of ResultSet object, which is not implementing java.io.Serializable , so that, it is not possible to transfer in the network, but, in the case of HQL, if we retrive records then that records will be stored in Collection objects, which are Serializable bydefault, so that, we are able to carry these objects in the network. HQL is database independent query language, but, SQL is database dependent query language. In case of Hibernate applications, if we process any HQL query then Hibernate Software will convert that HQL Query into database dependent SQL Query and Hibernate software will execute that generated SQL query.

Note: HQL is not suitable where we want to execute Database dependent sql queries

EX: PL/SQL procedures and functions are totally database dependent, where we are unable to use HQl queries.

Procedure to use HQL queries in Hibernate Applications

  • Represent HQL query by creating Query object.
  • Apply custom properties on HQl Query or on Query object.
  • Execute HQL Query
  • Represent HQL query by creating Query object.

Query object is able to store HQL query, to represent Query object Hibernate has provided a predefined interface in the form of "org.hibernate.Query".

To get Query object we have to use the following method from org.hibernate.Session .

public Query createQuery(String hql_Query)

EX: Query q = s.createQuery("from Employee");

  • Apply custom properties on HQL Query or on Query object.

In hibernate applications, after getting Query object we have to set the custom properties like providing fetch size , making the results as Cache results and read only results, providing start record position and max no of records,..... To perform all these custom propertties we have to use the following methods.

  • public void setFetchSize(int size)
  • public void setCacheable(boolean b)
  • public void setMaxResults(int value)
  • public void setFirstResult(int value)
  • public void setReadOnly(boolean b)
  • public void setComment(String comment)
  • public void setTimeOut(int time)

EX:

q.setFetchSize(10); q.setCacheable(true); q.setMaxResults(10); q.setFirstResult(5); q.setReadOnly(true); q.setComment("Employee Details"); q.setTimeOut(10000);

Execute HQL Query

To execute HQl queries we will use the following methods.

  • public List list()

 It will execute HQl query and generate the results in the form of List.

Example50
JCode Cell
1 
2List<Employee> list = query.list();
3System.out.println("ENO\tENAME\tESAL\tEADDR");
4System.out.println("------------------------------");
5for(Employee e: list) {
6 System.out.print(e.getEno()+"\t");
7 System.out.print(e.getEname()+"\t");
8 System.out.print(e.getEsal()+"\t");
9 System.out.println(e.getEaddr());
10}
11

Execute HQL Query

  • public Iterator iterate()

 It will execute HQL query and generate the results in the form of Iterator.

Example51
JCode Cell
1 
2Iterator<Employee> it = query.iterate();
3 System.out.println("ENO\tENAME\tESAL\tEADDR");
4 System.out.println("------------------------------");
5 while(it.hasNext()) {
6 Employee e = (Employee)it.next();
7 System.out.print(e.getEno()+"\t");
8 System.out.print(e.getEname()+"\t");
9 System.out.print(e.getEsal()+"\t");
10 System.out.println(e.getEaddr());
11}
12

Execute HQL Query

  • public ScrollableResults scoll()

 It able to execute HQl query and generate the results in form of ScrollableResults, which is same as ScrollableResultSet object , it allows to read data in both forward and backward directions.

Note: In the case of ScrollableResults we are able to use the following methods inorder to retrive data.

public boolean next() publci boolean previous() public void first() public void last() public Object get(int position)

Example52
JCode Cell
1 
2ScrollableResults results = query.scroll();
3 System.out.println("Employee Details in Forward Direction");
4 System.out.println("ENO\tENAME\tESAL\tEADDR");
5 System.out.println("------------------------------");
6 while(results.next()) {
7 Object[] obj = results.get();
8 for(Object o: obj) {
9 Employee e = (Employee)o;
10 System.out.print(e.getEno()+"\t");
11 System.out.print(e.getEname()+"\t");
12 System.out.print(e.getEsal()+"\t");
13 System.out.println(e.getEaddr());
14 }
15}
16 
17System.out.println("Employee Details in Backward Direction");
18System.out.println("ENO\tENAME\tESAL\tEADDR");
19System.out.println("------------------------------");
20while(results.previous()) {
21 Object[] obj = results.get();
22 for(Object o: obj) {
23 Employee e = (Employee)o;
24 System.out.print(e.getEno()+"\t");
25 System.out.print(e.getEname()+"\t");
26 System.out.print(e.getEsal()+"\t");
27 System.out.println(e.getEaddr());
28 }
29}
30

Execute HQL Query

  • public Object uniqueResult()

 It will execute HQl query and it will return only one result, if more than one result is identified then it will rise an Exception.

Example53
JCode Cell
1 
2Query query1 = session.createQuery("from Employee where eno= 111");
3 Object obj = query1.uniqueResult();
4 Employee e = (Employee)obj;
5 System.out.println("Employee Details");
6 System.out.println("----------------------");
7 System.out.println("Employee Number :"+e.getEno());
8 System.out.println("Employee Name :"+e.getEname());
9 System.out.println("Employee Salary :"+e.getEsal());
10 System.out.println("Employee Address:"+e.getEaddr());
11

Execute HQL Query

  • public int executeUpdate()

 It can be used to perform the database operations like insert, update, delete,..... and it will generate rowCount value.

Example54
JCode Cell
1 
2Query query = session.createQuery("update Employee set esal = esal + 500 where esal < 10000");
3Transaction tx = session.beginTransaction();
4int rowCount = query.executeUpdate();
5tx.commit();
6System.out.println("Records Updated :"+rowCount);
7

Execute HQL Query

Example55
JCode Cell
1 
2Query query = session.createQuery("delete from Employee where esal < 10000");
3Transaction tx = session.beginTransaction();
4int rowCount = query.executeUpdate();
5tx.commit();
6System.out.println("No of Records Deleted :"+rowCount);
7

Execute HQL Query — Employee.java

Example:

Example56
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47 
48}
49

Execute HQL Query — hibernate.cfg.xml

Example57
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_Sql">true</property>
14<mapping class="com.durgasoft.pojo.Employee"/>
15</session-factory>
16</hibernate-configuration>
17

Execute HQL Query — Test.java

Example58
JCode Cell
1 
2package com.durgasoft.test;
3 
4import java.util.Iterator;
5import java.util.List;
6 
7import org.hibernate.Query;
8import org.hibernate.ScrollableResults;
9import org.hibernate.Session;
10import org.hibernate.SessionFactory;
11import org.hibernate.boot.registry.StandardServiceRegistry;
12import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
13import org.hibernate.cfg.Configuration;
14 
15import com.durgasoft.pojo.Employee;
16 
17public class Test {
18 
19public static void main(String[] args) throws Exception{
20Configuration cfg = new Configuration();
21cfg.configure();
22StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
23builder = builder.applySettings(cfg.getProperties());
24StandardServiceRegistry registry = builder.build();
25SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
26Session session = sessionFactory.openSession();
27Query query = session.createQuery("from Employee");
28 
29System.out.println("Using list() method");
30System.out.println("-------------------------");
31List<Employee> list = query.list();
32System.out.println("ENO\tENAME\tESAL\tEADDR");
33System.out.println("------------------------------");
34for(Employee e: list) {
35 System.out.print(e.getEno()+"\t");
36 System.out.print(e.getEname()+"\t");
37 System.out.print(e.getEsal()+"\t");
38 System.out.println(e.getEaddr());
39}
40System.out.println();
41System.out.println("Using iterate() method");
42System.out.println("------------------------------");
43Iterator<Employee> it = query.iterate();
44System.out.println("ENO\tENAME\tESAL\tEADDR");
45System.out.println("------------------------------");
46while(it.hasNext()) {
47 Employee e = (Employee)it.next();
48 System.out.print(e.getEno()+"\t");
49 System.out.print(e.getEname()+"\t");
50 System.out.print(e.getEsal()+"\t");
51 System.out.println(e.getEaddr());
52}
53System.out.println();
54 
55System.out.println("Using scroll() method");
56System.out.println("----------------------------");
57ScrollableResults results = query.scroll();
58System.out.println("Employee Details in Forward Direction");
59System.out.println("ENO\tENAME\tESAL\tEADDR");
60System.out.println("------------------------------");
61while(results.next()) {
62 Object[] obj = results.get();
63 for(Object o: obj) {
64 Employee e = (Employee)o;
65 System.out.print(e.getEno()+"\t");
66 System.out.print(e.getEname()+"\t");
67 System.out.print(e.getEsal()+"\t");
68 System.out.println(e.getEaddr());
69 }
70}
71 
72System.out.println("Employee Details in Backward Direction");
73System.out.println("ENO\tENAME\tESAL\tEADDR");
74System.out.println("------------------------------");
75while(results.previous()) {
76 Object[] obj = results.get();
77 for(Object o: obj) {
78 Employee e = (Employee)o;
79 System.out.print(e.getEno()+"\t");
80 System.out.print(e.getEname()+"\t");
81 System.out.print(e.getEsal()+"\t");
82 System.out.println(e.getEaddr());
83 }
84}
85System.out.println();
86System.out.println("Using uniqueResult() method");
87System.out.println("--------------------------------------");
88Query query1 = session.createQuery("from Employee where eno= 111");
89Object obj = query1.uniqueResult();
90Employee e = (Employee)obj;
91System.out.println("Employee Details");
92System.out.println("----------------------");
93System.out.println("Employee Number :"+e.getEno());
94System.out.println("Employee Name :"+e.getEname());
95System.out.println("Employee Salary :"+e.getEsal());
96System.out.println("Employee Address:"+e.getEaddr());
97 
98session.close();
99sessionFactory.close();
100}
101}
102

Example on executeUpdate() method to perform update and delete operations — Employee.java

Example59
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47 
48}
49

Example on executeUpdate() method to perform update and delete operations — hibernate.cfg.xml

Example60
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_Sql">true</property>
14<mapping class="com.durgasoft.pojo.Employee"/>
15</session-factory>
16</hibernate-configuration>
17

Test.Java — Employee1.java

  • package com.durgasoft.test;
  • import java.util.Iterator;
  • import java.util.List;
  • import org.hibernate.Query;
  • import org.hibernate.ScrollableResults;
  • import org.hibernate.Session;
  • import org.hibernate.SessionFactory;
  • import org.hibernate.Transaction;
  • import org.hibernate.boot.registry.StandardServiceRegistry;
  • import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  • import org.hibernate.cfg.Configuration;
  • import com.durgasoft.pojo.Employee;
  • public class Test {
  • public static void main(String[] args) throws Exception{
  • Configuration cfg = new Configuration();
  • cfg.configure();
  • StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
  • builder = builder.applySettings(cfg.getProperties());
  • StandardServiceRegistry registry = builder.build();
  • SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
  • Session session = sessionFactory.openSession();
  • Query query1 = session.createQuery("update Employee set esal = esal + 500 where esal <

10000");

  • Transaction tx = session.beginTransaction();
  • int rowCount = query1.executeUpdate();
  • tx.commit();
  • System.out.println("Records Updated :"+rowCount);
  • Query query2 = session.createQuery("delete from Employee where esal < 10000");
  • Transaction tx = session.beginTransaction();
  • int rowCount = query2.executeUpdate();
  • tx.commit();
  • System.out.println("No of Records Deleted :"+rowCount);
  • session.close();
  • sessionFactory.close();

In HQL , we are able to use "insert" query to copy multiple records from one table to another table , not to insert a record into the database table directly.

EX:

Query query = session.createQuery("insert into Employee2(eno,ename,esal,eaddr)select e.eno, e.ename, e.esal, e.eaddr from Employee1 as e"); Transaction tx = session.beginTransaction(); int rowCount = query.executeUpdate(); tx.commit();

Example:

Example61
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee1 {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35 
36}
37

Test.Java — Employee2.java

Example62
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee2 {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35 
36}
37

Test.Java — Employee1.hbm.xml

Example63
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee1" table="emp1">
8<id name="eno" column="ENO"/>
9<property name="ename" column="ENAME"/>
10<property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13</hibernate-mapping>
14

Test.Java — Employee2.hbm.xml

Example64
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee2" table="emp2">
8<id name="eno" column="ENO"/>
9<property name="ename" column="ENAME"/>
10<property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13</hibernate-mapping>
14

Test.Java — hibernate.cfg.xml

Example65
JCode Cell
1 
2<!DOCTYPE hibernate-configuration PUBLIC
3"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6<session-factory>
7<property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
8<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9<property name="connection.user">system</property>
10<property name="connection.password">durga</property>
11<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
12<property name="hibernate.show_sql">true</property>
13<mapping resource="Employee1.hbm.xml"/>
14<mapping resource="Employee2.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

Test.Java — Test.java

Example66
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Query;
5import org.hibernate.Session;
6import org.hibernate.SessionFactory;
7import org.hibernate.Transaction;
8import org.hibernate.boot.registry.StandardServiceRegistry;
9import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10import org.hibernate.cfg.Configuration;
11 
12public class Test {
13 
14public static void main(String[] args)throws Exception {
15Configuration config = new Configuration();
16config.configure();
17StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
18builder = builder.applySettings(config.getProperties());
19StandardServiceRegistry registry = builder.build();
20SessionFactory sessionFactory = config.buildSessionFactory(registry);
21Session session = sessionFactory.openSession();
22Query query = session.createQuery("insert into Employee2(eno,ename,esal,eaddr)select e.eno,e.ename,e.esal,e.eaddr from Employee1 as e");
23Transaction tx = session.beginTransaction();
24int rowCount = query.executeUpdate();
25tx.commit();
26System.out.println("Employee details are transfered from emp1 to emp2");
27session.close();
28sessionFactory.close();
29}
30}
31

Test.Java — Employee1.java

The above Example with single mapping file with two pojo classes configuration

Example:

Example67
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee1 {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35 
36}
37

Test.Java — Employee2.java

Example68
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee2 {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35}
36

Test.Java — Employee.hbm.xml

Example69
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee1" table="emp1">
8<id name="eno" column="ENO"/>
9<property name="ename" column="ENAME"/>
10<property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13<class name="com.durgasoft.pojo.Employee2" table="emp2">
14<id name="eno" column="ENO"/>
15<property name="ename" column="ENAME"/>
16<property name="esal" column="ESAL"/>
17<property name="eaddr" column="EADDR"/>
18</class>
19</hibernate-mapping>
20

Test.Java — hibernate.cfg.xml

Example70
JCode Cell
1 
2<!DOCTYPE hibernate-configuration PUBLIC
3"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6<session-factory>
7<property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
8<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9<property name="connection.user">system</property>
10<property name="connection.password">durga</property>
11<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
12<property name="hibernate.show_sql">true</property>
13<mapping resource="Employee.hbm.xml"/>
14<!-- <mapping resource="Employee2.hbm.xml"/> -->
15</session-factory>
16</hibernate-configuration>
17

Test.Java — Test.java

Example71
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Query;
5import org.hibernate.Session;
6import org.hibernate.SessionFactory;
7import org.hibernate.Transaction;
8import org.hibernate.boot.registry.StandardServiceRegistry;
9import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10import org.hibernate.cfg.Configuration;
11 
12public class Test {
13 
14public static void main(String[] args)throws Exception {
15Configuration config = new Configuration();
16config.configure();
17StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
18builder = builder.applySettings(config.getProperties());
19StandardServiceRegistry registry = builder.build();
20SessionFactory sessionFactory = config.buildSessionFactory(registry);
21Session session = sessionFactory.openSession();
22Query query = session.createQuery("insert into Employee2(eno,ename,esal,eaddr)select e.eno,e.ename,e.esal,e.eaddr from Employee1 as e");
23Transaction tx = session.beginTransaction();
24int rowCount = query.executeUpdate();
25tx.commit();
26System.out.println("Employee details are transfered from emp1 to emp2");
27session.close();
28sessionFactory.close();
29}
30}
31

Above Example With Annotations — Employee1.java

Example72
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee1 {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47 
48}
49

Above Example With Annotations — Employee2.java

Example73
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp2")
11public class Employee2 {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22public int getEno() {
23return eno;
24}
25public void setEno(int eno) {
26this.eno = eno;
27}
28public String getEname() {
29return ename;
30}
31public void setEname(String ename) {
32this.ename = ename;
33}
34public float getEsal() {
35return esal;
36}
37public void setEsal(float esal) {
38this.esal = esal;
39}
40public String getEaddr() {
41return eaddr;
42}
43public void setEaddr(String eaddr) {
44this.eaddr = eaddr;
45}
46 
47 
48}
49

Above Example With Annotations — hibernate.cfg.xml

Example74
JCode Cell
1 
2<!DOCTYPE hibernate-configuration PUBLIC
3"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6<session-factory>
7<property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
8<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9<property name="connection.user">system</property>
10<property name="connection.password">durga</property>
11<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
12<property name="hibernate.show_sql">true</property>
13
📝 Key Takeaways
  • Key ideas of Hibernate - Connection Pooling (Proxool, JNDI) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end