Hibernate
Hibernate
com/hibernate6pmnotes
Hibernate:
—---------
1. Introduction
2. Steps to prepare First Hibernate Application
3. Primary Key Generation Algorithms
4. Auto Generation Tools[Schema Export and Schema Update]
5. Bulk Updations
[HQL, Native SQL, Criterion API]
6. Hibernate Filters
7. Hibernate Transaction Management
8. Hibernate Connection pooling Mechanisms
9. Hibernate Mappings
1. Basic OR Mapping
2. Component Mapping
3. Inheritance Mapping
4. Associations Mapping
—-------
—-------
Introduction:
—-------------
Enterprise Application:
Enterprise application is a Software application, it will be designed for an
enterprise in order to simplify their internal business processing.
Business Layer:
—---------------
The main purpose of this layer is to define and execute all the business
rules and regulations which are required by the clients.
To prepare Business Logics we will use the components like Servlets, Daos,
Java Beans, EJB Session Beans,.....
Persistence Layer:
—------------------
The main purpose of the Persistence layer is to interact with the database in
order to perform the database operations from the enterprise applications.
To perform Data persistence w.r.t the java applications we will use the
following persistence mechanisms.
With the above Steps, Serialization will be performed and the Serialized data
will be sent to the emp.txt file.
Steps to Perform Deserialization:
—---------------------------------
1. Create FileInputStream:
FileInputStream fis = new FileInputStream(“emp.txt”);
To overcome all the above problems we have to use JDBC Persistence Mechanism.
ORM:
—---
ORM: Object Relational Mapping
ORM: ORM is a design approach, it is able to provide the mapping between the
object oriented data model elements and the Relational Data model elements
either through XML file or through annotations.
1. Granularity Mismatch.
2. Subtypes mismatch.
3. Associations Mismatch.
4. Identity Mismatch.
—-----
—-----
Granularity Mismatch:
—---------------------
The number of classes which we have used in the Object oriented data model is
called Granularity.
The number of tables which we have used in the Relational data model is
called Granularity.
IN an enterprise application, as per the requirement we may use the number of
classes to represent data in Object Oriented data model and we may use the
number tables in the relational data model, In the object oriented data model
the granularity and the Relational Data Model granularity may not be matched,
in this situation we may get less data persistence in the enterprise
applications.
Subtypes Mismatch:
—------------------
In enterprise applications, we will define inheritance relations between
entity classes in the Object Oriented Data model in order to improve code
reusability.
In the relational data model, we will define the relations between table in
multiple ways like PK-FK, or a single table for all columns,....
In the above context, both the data models are having their own approaches of
representing data , it is the subtypes mismatches between Object oriented
data model and the relation data models, it will reduce data persistence in
the enterprise applications.
Associations Mismatch:
—----------------------
In the Object orientation data model, we are able to use associations to
provide communication between entities and to improve data navigation between
entities.
In the Relational Data Model , to achieve the associations we may use the
number of alternatives like by using PK-FK relationships or by providing a
Join column or by using a Join table.
One-To-One Mapping
One-To-Many Mapping
Many-To-One Mapping
Many-To-Many Mapping
Identity Mismatch:
—--------------------
IN the Object oriented Data Model, to check whether two objects are equals or
not we will use either == operator or equals() method.
In the above context, there is a mismatch about the equality check, it will
reduce data persistence.
IN the above context, ORM is able to provide mapping between both data models
in order to check the equality between two objects.
Hibernate is lightweight.
Hibernate is a tool, which implements ORM rules and regulations as per the
JPA guidelines in order to provide data persistence in the enterprise
applications.
Hibernate History:
—-------------------
Author: Gavin King
Objective: To simplify data persistence in enterprise applications.
Type: ORM Product
OPEN / Licenced: Open Source Software
Initial Version: Hibernate 1.x
Latest Version: Hibernate 6.x
Designed on : Java
Website : www.hibernate.org
Hibernate Features:
—-------------------
1. Hibernate is Database independent, it will be used for any type of
database.
2. Hibernate is suitable for all the types of applications like web
applications, distributed applications, standalone applications…..
3. Hibernate is able to provide very good support for associations and
joins.
4. Hibernate has annotation support to reduce XML dependency.
5. Hibernate has its own implementations for primary key generation
algorithms.
6. Hibernate has a very good Collection support while performing database
operations.
7. Hibernate has its own query language in the form of HQL.
8. Hibernate has its own implementations for the Cache mechanisms to hold
the results in order to reuse the same results in the applications.
9. Hibernate has a very good Connection pooling mechanism.
10. Hibernate is supported by almost all the servers and IDEs
11. In Hibernate applications, it is not required to write sql queries.
12. Hibernate is providing very good Transactions support.
Hibernate Architecture:
—----------------------
Where the Hibernate Configuration file will have the hibernate configuration
details like Driver class name, Driver URL, database user name, database
password, database dialect information,.... Which are required to establish
connection with the database.
Where the Hibernate mapping file will provide the mapping details between the
POJO class , POJO class properties with the database table name and the
database column names,....
When we activate Hibernate software , Hibernate Software will read all the
hibernate configuration details from the configuration file and Hibernate
Software will create connections with the database and Hibernate software
will make ready the mapping file.
Create a Java Project in Eclipse IDE and attach all the hibernate dependent
jar files in the build path:
—--------------------------------------------------------------------------
After creating a java project in the eclipse IDE, provide the following jar
files inside the project build path.
1. hibernate3.jar
2. antlr-2.7.6.jar
3. commons-collections-3.1.jar
4. dom4j-1.6.1.jar
5. javassist-3.12.0.GA.jar
6. jta-1.1.jar
7. slf4j-api-1.6.1.jar
Apart from all the above jar files we must add a driver jar file in the
project build path.
ojdbc11.jar
mysql-connector-j-8.0.33.jar
To prepare POJO classes we have to use the following rules and regulations.
1. Prepare POJO classes as per the Database tables and their columns.In
this case , POJO class name and its properties need not to be matched
with the table name and its column names, but we must maintain the
compatible data types.
Where the main purpose of the public in the POJO class declaration is
to bring POJO class scope to the Hibernate software in order to create
objects to the POJO class.
Where the main purpose of declaring POJO class as a non abstract class
is to allow the creation of objects for the POJO class.
Where the main purpose of declaring POJO class as a non final class is
to allow inheritance between POJO classes in order to improve code
reusability.
5. If we want to compare two POJO class objects with our own comparison
mechanisms then it is suggestible to override equals() method.
6. If we want to provide our own mechanisms to generate Hashcode values to
the objects in order to arrange the elements in the collections like
HashSet then it is suggestible to override hashcode() method in the
POJO classes.
EX:
public class Employee implements java.io.Serializable{
private int eno;
private String ename;
private float esal;
private String eaddr;
setXXX() and getXXX();
}
<!DOCTYPE ….>
<hibernate-mapping>
<class name=”--” table=”--”>
<id name=”--” column=”--”/>
<property name=”--” column=”--”/>
—----
—----
</class>
</hibernate-mapping>
Where <id> tag is able to provide the mapping between the id property of the
POJO class and the primary key column in the table.
Where <property> tag will provide the mapping between normal property from
the POJO class and the normal column from the database table.
EX:
<!DOCTYPE …. >
<hibernate-mapping>
<class name=”com.durgasoft.beans.Employee” table=”emp1”>
<id name=”eno” column=”eno”/>
<property name=”ename” column=”ename”/>
<property name=”esal” column=”esal”/>
<property name=”eaddr” column=”eaddr”/>
</class>
</hibernate-mapping>
If we use the database table emp1 like below then it is optional to provide
column attribute
emp1
ENO|ENAME|ESAL|EADDR
EX:
<!DOCTYPE …. >
<hibernate-mapping>
<class name=”com.durgasoft.beans.Employee” table=”emp1”>
<id name=”eno” />
<property name=”ename” />
<property name=”esal” />
<property name=”eaddr” />
</class>
</hibernate-mapping>
1. Connection COnfigurations
2. Transactions configurations
3. Cache mechanisms configurations
4. Connection pooling Configurations
—----
—----
Where the “name” attribute in the <property> tag will provide property name.
In the hibernate configuration file we have to provide value to the property
in the body of the <property> tag.
EX:
<hibernate-configuration>
<sessionfactory>
<property name=”hibernate.connection.driver_class”>
com.mysql.cj.jdbc.Driver
</property>
<property name=”hibernate.connection.url”>
jdbc:mysql://localhost:3306/durgadb
</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”>root</property>
<property name=”hibernate.dialect”>
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource=”/Employee.hbm.xml”/>
</sessionfactory>
</hibernate-configuration>
Hibernate Test Application / Hibernate Client Application:
—---------------------------------------------------------
The main purpose of the Hibernate Test Applications is
1. Activate Hibernate Software.
2. Create Persistence Objects.
3. Perform the persistence operations.
To prepare the Hibernate Test application we have to use the following steps.
EX:
Configuration cfg = new Configuration();
The configure(URL url) method is able to take the location URL of the
configuration in the internet and it is able to get all the
configuration details through the provided url into the COnfiguration
object.
EX:
Session session = sessionFactory.openession();
To get Transaction object we have to use the following method from the
Session.
session.close();
sessionFactory.close();
EX-1:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.12.0.GA.jar
required\jta-1.1.jar
ojdbc11.jar
Slf4j-api-1.6.1.jar
Employee.java
package com.durgasoft.entities;
public class Employee {
Employee.hbm.xml
hibernate.cfg.xml
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.durgasoft.entities.Employee;
public class Test {
public static void main(String[] args) throws Exception {
SessionFactory sessionFactory =
configuration.buildSessionFactory();
session.close();
sessionFactory.close();
}
}
Hibernate Mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
Hibernate Configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
EX:
Employee.java
package com.durgasoft.entities;
public class Employee {
Employee.hbm.xml
hibernate.cfg.xml
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.durgasoft.entities.Employee;
public class Test {
public static void main(String[] args) {
SessionFactory sessionFactory =
configuration.buildSessionFactory();
session.close();
sessionFactory.close();
}
}
persist() method will insert an object as a record into the database table,
but it does not return primary key value.
EX:
Transaction transaction = session.beginTransaction();
session.persist(employee);
transaction.commit();
System.out.println("Employee Inserted Successfully");
EX:
Employee.java
package com.durgasoft.entities;
public class Employee {
Employee.hbm.xml
myconfig.xml
Employee Details
----------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 5000.0
Employee Address : Hyd
If we want to work with the MySQL database we have to use the following
steps.
load() method can be used to get an object from the Database table, if the
record is not available then the load() method will raise an exception like
org.hibernate.ObjectNotFoundException
EX:
Employee.java
package com.durgasoft.entities;
public class Employee {
private int eno;
private String ename;
private float esal;
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;
}
@Override
public String toString() {
return "Employee [eno=" + eno + ", ename=" + ename + ", esal=" +
esal + ", eaddr=" + eaddr + "]";
}
}
Employee.hbm.xml
hibernate.cfg.xml
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.durgasoft.entities.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory =
configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.load(Employee.class, 222);
System.out.println(employee);
/*
* if(employee == null) { System.out.println("Employee Does Not
Exist"); }else {
* System.out.println("Employee Details");
* System.out.println("-----------------------");
* System.out.println("Employee Number :
"+employee.getEno());
* System.out.println("Employee Name :
"+employee.getEname());
* System.out.println("Employee Salary :
"+employee.getEsal());
* System.out.println("Employee Address :
"+employee.getEaddr()); }
*/
}
}
saveOrUpdate() method will save the record if the record is not available ,
if the record is available then it will perform update operations.
EX:
Employee.java
package com.durgasoft.beans;
public class Employee {
Employee.hbm.xml
hibernate.cfg.xml
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory =
configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("XXX");
employee.setEsal(9000);
employee.setEaddr("Chennai");
Transaction transaction = session.beginTransaction();
session.update(employee);
transaction.commit();
System.out.println("Employee Updated Successfully");
session.close();
sessionFactory.close();
}
}
EX:
Employee.java
package com.durgasoft.beans;
public class Employee {
}
Employee.hbm.xml
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory =
configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = new Employee();
employee.setEno(222);
employee.setEname("YYY");
employee.setEsal(8000);
employee.setEaddr("Pune");
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction.commit();
System.out.println("Employee Updated Successfully");
session.close();
sessionFactory.close();
}
}
EX:
Employee.java
package com.durgasoft.beans;
public class Employee {
Employee.hbm.xml
hibermate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_Class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3300/durgadb</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Test.java
package com.durgasoft.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.durgasoft.beans.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory =
configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = new Employee();
employee.setEno(222);
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.entities.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3300/durgadb</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.entities.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app08</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
</project>
EX:
Employee.java
package com.durgasoft.beans;
import java.io.Serializable;
EmployeeController.java
package com.durgasoft.controller;
import com.durgasoft.beans.Employee;
import com.durgasoft.factories.EmployeeServiceFactory;
import com.durgasoft.service.EmployeeService;
import java.io.BufferedReader;
import java.io.InputStreamReader;
EmployeeService.java
package com.durgasoft.service;
import com.durgasoft.beans.Employee;
EmployeeServiceImpl.java
package com.durgasoft.service;
import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import com.durgasoft.factories.EmployeeDaoFactory;
@Override
public String updateEmployee(Employee employee) {
String status = employeeDao.update(employee);
return status;
}
@Override
public String deleteEmployee(int eno) {
String status = employeeDao.delete(eno);
return status;
}
}
EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
EmployeeDaoImpl.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;
import com.durgasoft.factories.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
@Override
public Employee search(int eno) {
Employee employee = null;
try{
Session session = sessionFactory.openSession();
employee = (Employee) session.get("com.durgasoft.beans.Employee",
eno);
}catch (Exception exception){
exception.printStackTrace();
}
return employee;
}
@Override
public String update(Employee employee) {
String status = "";
try{
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(employee);
transaction.commit();
status = "SUCCESS";
}catch (Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
@Override
public String delete(int eno) {
String status = "";
try{
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee();
employee.setEno(eno);
session.delete(employee);
transaction.commit();
status = "SUCCESS";
}catch (Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
}
Main.java
package com.durgasoft;
import com.durgasoft.controller.EmployeeController;
import com.durgasoft.factories.EmployeeControllerFactory;
import com.durgasoft.factories.HibernateUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
System.out.println("------------------------------------");
employeeController.deleteEmployee();
break;
case 5:
System.out.println("**********Thank You for using Employee
Management Application ******");
System.exit(0);
break;
default:
System.out.println("INvalid Entry, please provide the
numbers from 1, 2,3,4 and 5");
break;
}
}
}
}
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">durga</property>
<property
name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app11</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>23.2.0.0</version>
</dependency>
</dependencies>
</project>
EX:
loginform.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user Login Page</title>
</head>
<body>
<h2 style="color: red; text-align: center">Durga Software Solutions</h2>
<h3 style="color: blue; text-align: center">User Login Form</h3>
<form method="post" action="./login">
<table style="margin-left: auto; margin-right: auto">
<tr>
<td>User Name</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="upwd"></td>
</tr>
<tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login Status</title>
</head>
<body>
<h2 style="color: red; text-align: center">Durga Software Solutions</h2>
<h3 style="color: blue; text-align: center">User Login Status</h3>
<h1 style="color: green; text-align: center">Login Success</h1>
<h4 style="text-align: center">
<a href="./loginform.html">|Login Page|</a>
</h4>
</body>
</html>
failure.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login Status</title>
</head>
<body>
<h2 style="color: red; text-align: center">Durga Software Solutions</h2>
<h3 style="color: blue; text-align: center">User Login Status</h3>
<h1 style="color: green; text-align: center">Login Failure</h1>
<h4 style="text-align: center">
<a href="./loginform.html">|Login Page|</a>
</h4>
</body>
</html>
LoginServlet.java
package com.durgasoft.app10.servlets;
import com.durgasoft.app10.action.LoginAction;
import com.durgasoft.app10.beans.User;
import com.durgasoft.app10.factory.LoginActionFactory;
import com.durgasoft.app10.util.HibernateUtil;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
User user = new User();
user.setUname(uname);
user.setUpwd(upwd);
LoginAction loginAction = LoginActionFactory.getLoginAction();
String status = loginAction.checkLogin(user);
RequestDispatcher requestDispatcher = null;
if(status.equals("success")){
requestDispatcher = request.getRequestDispatcher("success.html");
requestDispatcher.forward(request, response);
}else{
requestDispatcher = request.getRequestDispatcher("failure.html");
requestDispatcher.forward(request, response);
}
}
}
LoginAction.java
package com.durgasoft.app10.action;
import com.durgasoft.app10.beans.User;
import com.durgasoft.app10.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
LoginActionFactory.java
package com.durgasoft.app10.factory;
import com.durgasoft.app10.action.LoginAction;
HibernateUtil.java
package com.durgasoft.app10.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<welcome-file-list>
<welcome-file>loginform.html</welcome-file>
</welcome-file-list>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app10</artifactId>
<version>1.0-SNAPSHOT</version>
<name>app10</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<junit.version>5.9.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin> </plugins>
</build>
</project>
EX:
—--
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="text-align: center; color: white">
DURGA SOFTWARE SOLUTIONS
</h1>
</body>
</html>
menu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2 style="color: red; text-align: center">
<marquee>
Welcome To Durga Software Solutions
</marquee>
</h2>
</body>
</html>
footer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3 style="text-align: center; color: white">
Durgasoft India Private Ltd. , 202, HMDA, Mitrivanam, Ameerpet, Hyd-38.
</h3>
</body>
</html>
addform.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="add.do">
<table style="margin-left: auto; margin-right: auto">
<tr>
<td>Student Id</td>
<td><input type="text" name="sid"></td>
</tr>
<tr>
<td>Student Name</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>Student Address</td>
<td><input type="text" name="saddr"></td>
</tr>
<tr>
<td><input type="submit" value="ADD"></td>
</tr>
</table>
</form>
</body>
</html>
Searchform.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="search.do">
<table style="margin-left: auto; margin-right: auto">
<tr>
<td>Student Id</td>
<td><input type="text" name="sid"></td>
</tr>
<tr>
<td><input type="submit" value="SEARCH"></td>
</tr>
</table>
</form>
</body>
</html>
updateform.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="editform.do">
<table style="margin-left: auto; margin-right: auto">
<tr>
<td>Student Id</td>
<td><input type="text" name="sid"></td>
</tr>
<tr>
<td><input type="submit" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
deleteform.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="delete.do">
<table style="margin-left: auto; margin-right: auto">
<tr>
<td>Student Id</td>
<td><input type="text" name="sid"></td>
</tr>
<tr>
<td><input type="submit" value="DELETE"></td>
</tr>
</table>
</form>
</body>
</html>
welcomehome.jsp
addhome.jsp
searchhome.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Student Management System Home</title>
</head>
<body>
<table style="width: 100%; height: 100%">
<tr style="height: 20%">
<td style="background-color: maroon;" colspan="2">
<jsp:include page="header.html"/>
</td>
</tr>
<tr style="height: 65%">
<td style="width: 20%; background-color: bisque;">
<jsp:include page="menu.html"/>
</td>
<td style="background-color: aqua;">
<jsp:include page="searchform.html"/>
</td>
</tr>
</td>
</tr>
<tr style="height: 15%;">
<td style="background-color: blue;" colspan="2">
<jsp:include page="footer.html"/>
</td>
</tr>
</table>
</body>
</html>
updatehome.jsp
deletehome.jsp
statushome.jsp
editformhome.jsp
Student.java
package com.durgasoft.app12.beans;
ControllerServlet.java
package com.durgasoft.app12.controller;
import com.durgasoft.app12.beans.Student;
import com.durgasoft.app12.factory.StudentDaoFactory;
import com.durgasoft.app12.factory.StudentServiceFactory;
import com.durgasoft.app12.service.StudentService;
import com.durgasoft.app12.util.HibernateUtil;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String status = "";
String sid = "";
String sname = "";
String saddr = "";
Student student = null;
RequestDispatcher requestDispatcher = null;
StudentService studentService =
StudentServiceFactory.getStudentService();
String requestURI = request.getRequestURI();
if(requestURI.endsWith("add.do")){
sid = request.getParameter("sid");
sname = request.getParameter("sname");
saddr = request.getParameter("saddr");
student = new Student();
student.setSid(sid);
student.setSname(sname);
student.setSaddr(saddr);
Student student1 = studentService.searchStudent(sid);
if(student1 == null) {
status = studentService.addStudent(student);
}else{
status = "Student Existed Already";
}
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}
if(requestURI.endsWith("search.do")){
sid = request.getParameter("sid");
student = studentService.searchStudent(sid);
if(student == null){
status = "Student Does Not Exist";
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}else {
request.setAttribute("student", student);
requestDispatcher =
request.getRequestDispatcher("studentdetailshome.jsp");
requestDispatcher.forward(request, response);
}
}
if(requestURI.endsWith("editform.do")){
sid = request.getParameter("sid");
student = studentService.searchStudent(sid);
if(student == null){
status = "Student Does Not Exist";
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}else{
request.setAttribute("student", student);
requestDispatcher =
request.getRequestDispatcher("editformhome.jsp");
requestDispatcher.forward(request, response);
}
}
if(requestURI.endsWith("update.do")){
sid = request.getParameter("sid");
sname = request.getParameter("sname");
saddr = request.getParameter("saddr");
student = new Student();
student.setSid(sid);
student.setSname(sname);
student.setSaddr(saddr);
status = studentService.updateStudent(student);
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}
if(requestURI.endsWith("delete.do")){
sid = request.getParameter("sid");
student = studentService.searchStudent(sid);
if(student == null){
status = "Student Does Not Exist";
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}else{
status = studentService.deleteStudent(sid);
request.setAttribute("status", status);
requestDispatcher =
request.getRequestDispatcher("statushome.jsp");
requestDispatcher.forward(request, response);
}
}
}
}
StudentService.java
package com.durgasoft.app12.service;
import com.durgasoft.app12.beans.Student;
StudentServiceImpl.java
package com.durgasoft.app12.service;
import com.durgasoft.app12.beans.Student;
import com.durgasoft.app12.dao.StudentDao;
import com.durgasoft.app12.factory.StudentDaoFactory;
@Override
public Student searchStudent(String sid) {
Student student = studentDao.search(sid);
return student;
}
@Override
public String updateStudent(Student student) {
String status = studentDao.update(student);
return status;
}
@Override
public String deleteStudent(String sid) {
String status = studentDao.delete(sid);
return status;
}
}
StudentDao.java
package com.durgasoft.app12.dao;
import com.durgasoft.app12.beans.Student;
StudentDaoImpl.java
package com.durgasoft.app12.dao;
import com.durgasoft.app12.beans.Student;
import com.durgasoft.app12.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
@Override
public Student search(String sid) {
Student student = null;
try{
Session session = sessionFactory.openSession();
student = (Student) session.get(Student.class, sid);
}catch (Exception exception){
exception.printStackTrace();
}
return student;
}
@Override
public String update(Student student) {
String status = "";
try{
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(student);
transaction.commit();
status = "SUCCESS";
}catch (Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
@Override
public String delete(String sid) {
String status = "";
try{
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Student student = new Student();
student.setSid(sid);
session.delete(student);
transaction.commit();
status = "SUCCESS";
}catch (Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
}
StudentServiceFactory.java
package com.durgasoft.app12.factory;
import com.durgasoft.app12.service.StudentService;
import com.durgasoft.app12.service.StudentServiceImpl;
import com.durgasoft.app12.dao.StudentDao;
import com.durgasoft.app12.dao.StudentDaoImpl;
HibernateUtil.java
package com.durgasoft.app12.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
Student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.app12.beans.Student" table="student">
<id name="sid"/>
<property name="sname"/>
<property name="saddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3300/durgadb</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<welcome-file-list>
<welcome-file>welcomehome.jsp</welcome-file>
</welcome-file-list>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app12</artifactId>
<version>1.0-SNAPSHOT</version>
<name>app12</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<junit.version>5.9.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin> </plugins>
</build>
</project>
Q)Is it possible to connect with more than one Database in a single Hibernate
application?
—----------------------------------------------------------------------------
Ans:
—----
Yes, it is possible to connect with more than one database from a single
Hibernate application but we have to use the following conventions.
EX:
Student.java
package com.durgasoft.beans;
Student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Student" table="student">
<id name="sid"/>
<property name="sname"/>
<property name="saddr"/>
</class>
</hibernate-mapping>
hibernate-oracle-cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">durga</property>
<property
name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate-mysql-cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
oracleSession.close();
mysqlSession.close();
oracleSf.close();
mysqlSf.close();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app13</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>oracle</groupId>
<artifactId>oracle-ojdbc</artifactId>
<version>21-xe</version>
</dependency>
</dependencies>
</project>
In the Configuration file, in the <mapping> tag we have to use the “class”
attribute in place of resource attribute.
In Main class, we have an AnnotationConfiguration class in place of
Configuration class.
EX:
Employee.java
package com.durgasoft.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "emp1")
public class Employee {
@Id
@Column(name = "ENO")
private int eno;
@Column(name = "ENAME")
private String ename;
@Column(name = "ESAL")
private float esal;
@Column(name = "EADDR")
private String eaddr;
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.durgasoft.beans.Employee"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app14</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
1. Programmatic Approach
2. Declarative Approach
Programmatic Approach:
—----------------------
In this approach, we will not provide configuration files and we will provide
all the configuration details by using the following methods from the
Configuration class.
public void setProperty(String propName, String propValue)
public void addResource(String mappingFileName)
public void addAnnotatedClass(Class AnnotatedClass)
EX:
Employee.java
package com.durgasoft.beans;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
configuration.setProperty("hibernate.connection.driver_class","com.mysql.cj.j
dbc.Driver");
configuration.setProperty("hibernate.connection.url",
"jdbc:mysql://localhost:3306/durgadb");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQLDialect");
configuration.addResource("Employee.hbm.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.get(Employee.class, 111);
if(employee == null){
System.out.println("Employee Does Not Exist");
}else{
System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee NUmber : "+employee.getEno());
System.out.println("Employee Name : "+employee.getEname());
System.out.println("EDmployee Salary : "+employee.getEsal());
System.out.println("Employee Address : "+employee.getEaddr());
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
EX:
Employee.java
package com.durgasoft.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "emp1")
public class Employee {
@Id
private int eno;
private String ename;
private float esal;
private String eaddr;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
configuration.setProperty("hibernate.connection.driver_class","com.mysql.cj.j
dbc.Driver");
configuration.setProperty("hibernate.connection.url",
"jdbc:mysql://localhost:3306/durgadb");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQLDialect");
//configuration.addResource("Employee.hbm.xml");
configuration.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.get(Employee.class, 111);
if(employee == null){
System.out.println("Employee Does Not Exist");
}else{
System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee NUmber : "+employee.getEno());
System.out.println("Employee Name : "+employee.getEname());
System.out.println("EDmployee Salary : "+employee.getEsal());
System.out.println("Employee Address : "+employee.getEaddr());
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
Declarative Approach:
—--------------------
In the declarative approach, we will use either properties file or XML file
to provide all the configuration details instead of using java methods , in
this approach if we want to provide changes frequently in the configuration
details then we can perform changes in the properties file or in the xml
file, these changes does not require recompilation of the hibernate
application.
Properties file:
In this approach we will prepare a hibernate.properties file with all the
hibernate configuration details except mapping files configuration.
hibernate.properties
hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/durgadb
hibernate.connection.username =root
hibernate.connection.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
EX:
hibernate.properties
hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/durgadb
hibernate.connection.username =root
hibernate.connection.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
Employee.java
package com.durgasoft.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//@Entity
//@Table(name = "emp1")
public class Employee {
//@Id
private int eno;
private String ename;
private float esal;
private String eaddr;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
In the above application, if we use the different name to the properties file
, not hibernate.properties then we have to get all the configuration details
explicitly from the properties file by using FileInputStream and Properties
object.
After getting all the configuration details in the Properties class object we
have to set the Properties object to the COnfiguration object by using the
following method.
EX:
config.properties
hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/durgadb
hibernate.connection.username =root
hibernate.connection.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
Employee.java
package com.durgasoft.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//@Entity
//@Table(name = "emp1")
public class Employee {
//@Id
private int eno;
private String ename;
private float esal;
private String eaddr;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.FileInputStream;
import java.util.Properties;
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
XML File:
—--------
If we want to use an XML file to provide all the configuration details to the
Configuration object then we have to use the XML file name hibernate.cfg.xml.
When we access the configure() method, Hibernate software will search for the
configuration file with the name hibernate.cfg.xml , if it is not available
then hibernate software will raise an exception. If the hibernate.cfg.xml
file exists then the Hibernate software will get the data from the
configuration file and it will store that data in the Configuration object.
EX:
Employee.java
package com.durgasoft.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//@Entity
//@Table(name = "emp1")
public class Employee {
//@Id
private int eno;
private String ename;
private float esal;
private String eaddr;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
myconfig.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.FileInputStream;
import java.util.Properties;
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
1. Transient State.
2. Persistence State.
3. Detached State.
4. Removed State.
Transient STate:
—----------------
In Hibernate applications, when we create a POJO class object , automatically
that POJO class object will be in Transient state.
If the POJO class object is in Transient state then the Hibernate software is
not aware about the POJO class object.
IN this state, Hibernate Software is not providing synch between POJO class
objects and the Database table.
If we keep the POJO class object in the Transient state for a long time then
the POJO class object is eligible for the Garbage Collection.
Persistence State:
—--------------------
In Hibernate applications, when we access the methods like save(), persist(),
saveOrUpdate()... with the POJO class object , automatically that POJO class
object will be in the Persistence state.
If the POJO class object is in the Persistence state then the Hibernate
software is aware of the POJO class object.
Detached State:
—----------------
In Hibernate applications, when we access the methods like close(), clear(),
evict()... with the POJO class object , automatically that POJO class object
will be in the Detached state.
In Hibernate applications, if we access the methods like save(), update(),
saveOrUpdate()... then the POJO class object will come back to the
Persistence state from the Detched State.
If the POJO class object is in the Detached state then the Hibernate software
is shutdown and it is not aware about the POJO class object.
If we keep the POJO class object in the Transient state for a long time then
the POJO class object is eligible for the Garbage Collection.
Removed State:
—-------------
If we perform the operations like delete() over the Persistence object then
the POJO class object will come to the Removed State.
In Removed State, Hibernate software is not aware about the POJO class
object.
If the POJO class object is in the removed state then it is eligible for the
Garbage Collection, there is no chance to get back to the Persistence state.
1. SchemaExport
2. SchemaUpdate
3. CodeGeneration
Note: The above tools are useful to create tables in the databases when we
are working with the unknown databases.
SchemaExport
—------------
It is a class provided by the Hibernate software in the form of
org.hibernate.tool.hbm2ddl.SchemaExport
1. SchemaExport tool will take the name and location of the configuration
file which we provided as a parameter to the SchemaExport tool.
2. It will load and parse the configuration file.
3. It will find the name and location of the mapping file and perform
loading and parsing.
4. As per the mapping file data, SchemaExport will check whether the
provided table exists or not in the database.
5. If no table exists then SchemaExport tool will create a new table as
per the mapping file data.
6. If any table exists with the same name then the SchemaExport tool will
drop the existing table and create a new table.
To activate the SchemaExport tool we have to use the following command on the
command prompt.
D:\hbnapps>java org.hibernate.tool.hbm2ddl.SchameExport
–config=hibernate.cfg.xml
Note: To run the above command on the command prompt we must copy all the
hibernate jars in the C:\Java\jdk-version\lib\ext folder.
EX:
Employee.java
@Override
public String toString() {
return "Employee [eno=" + eno + ", ename=" + ename + ", esal=" +
esal + ", eaddr=" + eaddr + "]";
}
Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="emp20">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_Class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3300/durgadb</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
On Command prompt:
D:\Hibernate730\app20>javac Employee.java
D:\Hibernate730\app20>java org.hibernate.tool.hbm2ddl.SchemaExport
--config=hibernate.cfg.xml
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.
drop table if exists emp20
create table emp20 (eno integer not null, ename varchar(255), esal float,
eaddr varchar(255), primary key (eno))
Schema Update Tool:
—------------------
It is provided by the Hibernate software in the form of
org.hibernate.tool.hbm2ddl.SchemaUpdate.
If we activate the Schema Update tool then it will perform the following
actions.
1. The SchemaUpdate tool will take the name and location of the
configuration file which we provided as an input parameter.
2. SchemUpdate tool will load and parse the configuration file.
3. The SchemaUpdate tool will identify the name and location of the
mapping file from the configuration file.
4. The schemaUpdate tool will load and parse the mapping file.
5. As per the mapping file data , SchemaUpdate tool will check whether the
table exists or not in the database which we provided in the mapping
file .
6. If no table exists with the same name then the SchemaUpdate tool will
create a new table as per the mapping file details.
7. If the table exists in the database then the SChemaUpdate tool will
alter the table as per the mapping file configuration.
To activate the SchemaUpdate tool we have to use the following command on the
command prompt.
Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="emp20">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
<property name="equal"/>
<property name="edes"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_Class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3300/durgadb</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
D:\Hibernate730\app20>javac Employee.java
D:\Hibernate730\app20>java org.hibernate.tool.hbm2ddl.SchemaUpdate
--config=hibernate.cfg.xml\
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.
alter table emp20 add column edes varchar(255)
hibernate.hbm2ddl.auto.
1. create
2. update
3. create-drop
create: It is representing SchemaExport tool, it will create a table as per
the mapping file configuration details irrespective of the table existence.
EX:
Employee.java
package com.durgasoft.beans;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">Nagoor@786</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
Employee.java
package com.durgasoft.beans;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp2">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
<property name="equal"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">Nagoor@786</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
3. Create-drop:
It will create tables as per the mapping file configuration data when
SessionFactory object is created and it will drop the tables when the
SessionFactory object is destroyed.
EX:
Employee.java
package com.durgasoft.beans;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp5">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
<property name="equal"/>
</class>
</hibernate-mapping>
Hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">Nagoor@786</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>hbnapp01</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javassist/javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
4. Get all the configuration Details from the properties object to the
StandardServiceRegistryBuilder object:
builder = builder.applySettings(props);
In Short,
StandardServiceRegistry = new
StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
EX:
Employee.java
package com.durgasoft.beans;
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">Nagoor@786</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>hbnapp02</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
Primary Key Generation Algorithms:
—-----------------------------------
Primary key is a single column or the collection of columns in a table to
recognize the records individually.
To provide the primary key values as per the rules and regulations we have to
generate the primary key values automatically as part of the application.
To provide primary key values in the applications we have to use the Primary
key generation algorithms.
Almost all the persistence mechanisms have provided their own implementation
for the Primary key generation algorithms.
Hibernate has provided support for the following primary key generation
algorithms.
1. assigned
2. increment
3. sequence
4. identity
5. hilo
6. native
7. seq-hilo
8. select
9. UUID
10. GUID
11. foreign
Hibernate has provided all the primary key generation algorithms in the form
of a set of predefined classes like org.hibernate.id.XXXGenerator.
Where “class” attribute in the <generator> tag will take either the fully
qualified name of the Primary key generation algorithm or short name of the
primary key generation algorithm
Where the “<param>” tag will provide input parameter values to the Primary
key generation algorithms.
The “name” attribute in the <param> tag will take the parameter name and we
must provide the value of this parameter in the body part.
1. Assigned:
—-------------
This algorithm is the default primary key generation algorithm, it does not
require configuration in the mapping file.
This algorithm does not have its own implementation to generate primary key
values rather it asks the users to provide primary key values explicitly.
EX:
Employee.java
package com.durgasoft.beans;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno">
<generator class="org.hibernate.id.Assigned"/>
</id>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
<property name="connection.username">root</property>
<property name="connection.password">Nagoor@786</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
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;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>hbnapp03</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core
-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
2. Increment:
—-------------
1. This algorithm will generate the primary key value by incrementing one
the max value of the primary key column.
NewVal=max(PK_Column)+1
2. This algorithm is able to generate the primary key values of the data
types like short, int, long,...
3. This algorithm does not require input parameters.
4. This algorithm is supported by almost all the databases.
5. To represent this algorithm Hibernate has provided a short name in the
form of “increment” or a predefined class name
“org.hibernate.generator.IncrementGenerator”.
EX:
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno">
<generator class="increment"/>
</id>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
3. sequence:
—-------------
4. Identity:
—-------------
This algorithm is able to generate the primary key values on the basis of the
underlying database table provided identity column.
This algorithm is able to provide the primary key values of the data types
like short, int, long, ….
This algorithm is supported by almost all the databases which are supporting
Identity columns.
EX:
IN MySQL Database:
create table emp5(ENO int(5) primary key auto_increment,ENAME char(10), ESAL
float(5), EADDR char(10));
commit ;
In Mapping file:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp5">
<id name="eno">
<generator class="identity"/>
</id>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Hilo:
—-----
Hilo: High-Low
This algorithm is able to provide the primary key values on the basis of the
high values from the global resource[Some other table in the ame database]
and low value from the mapping file.
This algorithm is able to generate the primary key values of the data types
like short, int, long,...
EX:
In MySQL Database:
create table my_table(my_column int(3) primary key);
insert into my_table values(100);
commit ;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno">
<generator class="hilo">
<param name="table">my_table</param>
<param name="column">my_column</param>
<param name="max_lo">10</param>
</generator>
</id>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
Note: If we have not provided the table and column parameters in the mapping
file then the Hilo algorithm will search for the default global resource
table name like “hibernate_unique_key” and the default column name “next_hi”.
EX:
In MySQL Database:
create table hibernate_unique_key(next_hi int(5) primary key);
insert into hibernate_unique_key values(100);
commit ;
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno">
<generator class="hilo">
<!-- <param name="table">my_table</param>
<param name="column">my_column</param>-->
<param name="max_lo">10</param>
</generator>
</id>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>
native:
—-------