Nearby lessons
13 of 19Hibernate - Connection Pooling (Proxool, JNDI)
- 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;
Connection Pooling (Proxool, JNDI) — ClientApp.java
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.
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:
Transaction Management — oracle_cfg.xml
Transaction Management — mysql_cfg.xml
Transaction Management — Test.java
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;
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.
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:
hibernate.c3p0.max_statements — hibernate.cfg.xml
hibernate.c3p0.max_statements — Test.java
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:
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:
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:
Proxool Connection Pooling Mechanism — hibernate.cfg.xml
Proxool Connection Pooling Mechanism — proxool.xml
Proxool Connection Pooling Mechanism — Test.java
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"
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.
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:
hibernate.jndi.url — hibernate.cfg.xml
hibernate.jndi.url — Test.java
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.
Execute HQL Query
- public Iterator iterate()
It will execute HQL query and generate the results in the form of Iterator.
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)
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.
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.
Execute HQL Query
Execute HQL Query — Employee.java
Example:
Execute HQL Query — hibernate.cfg.xml
Execute HQL Query — Test.java
Example on executeUpdate() method to perform update and delete operations — Employee.java
Example on executeUpdate() method to perform update and delete operations — hibernate.cfg.xml
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:
Test.Java — Employee2.java
Test.Java — Employee1.hbm.xml
Test.Java — Employee2.hbm.xml
Test.Java — hibernate.cfg.xml
Test.Java — Test.java
Test.Java — Employee1.java
The above Example with single mapping file with two pojo classes configuration
Example:
Test.Java — Employee2.java
Test.Java — Employee.hbm.xml
Test.Java — hibernate.cfg.xml
Test.Java — Test.java
Above Example With Annotations — Employee1.java
Above Example With Annotations — Employee2.java
Above Example With Annotations — hibernate.cfg.xml
- Key ideas of Hibernate - Connection Pooling (Proxool, JNDI) explained simply
- Ready-to-use code examples
- Exam-style questions at the end