Hibernate JuneJuly

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 94

Hibernate

https://jar-download.com/artifacts/org.hibernate/hibernate-core

perspective

jdk 1.8

Eclipse

Mysql 8

Apache Tomcat

Hibernate
----------------------------------

JDBC --> JAVA Database Connectivity

// Step Load Load Driver Class


Class.forName("com.mysql.cj.jdbc.Driver");

// 2 Step

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName","root","ro
ot");

// 3 Step

Statement stmt=con.createStaement()

String sql="select * from tableName";


// Step 4
ResultSet rs=stmt.executeQuery(sql);

Step 5
// Loop

Why we are using Hibernate?

// Boiler Plate Code --> Means every time we are going write the same code

+ To avoid writing Boiler Plate Code

+ Sql queries are database independent in Hibernate[HQL]

HQL--> Hibernate Query Language

+ Checked Exception while during database Connectivity and other Operations

Hibernate convert these Checked Exception into UnChecked Exception.

+++++++++++++++++++++++++++
+++++++++++++++++++++++++++

Framework are of 2 Types

1: Invasive Framework

A developer need to extends or implements something

For Ex Servlet ,Structs

class Hello extends HttpServlet{

class A implements Servlet{

2: Non-Invasive Framework
A developer need not to be extends or implements something

Ex - Hibernate , Spring

+ Hibernate
----------------------

It is an ORM Tool(Object Relational Mapping)

Hibernate is an Open Source Technology created By JBoss

Hibernate is a middle layer between java and database.

Hibernate will used in both JAVASE Application as well


Web Application

What is JAVA Bean Class?

A class must be implements Serializable


A class must have private Fields
A class must have setter getters
A class must have constructor

such a class called as JAVA Bean

Ex
class A{

Ex

class B implements Serializable{


private int x;
B(){ }
public void setX(int x) {}
public int getX() { return x;}

What is POJO class ? [Plain Old JAVA Object]

A class which does not exceeds core java api called as POJO class

class B implements Serializable{


private int x;

B(){ }
public void setX(int x) {}
public int getX() { return x;}

----------
class A{

class C{

public void sayHello(){ }


}

// D is not a POJO class


class D implements Servlet{

-------------------------------------------

Hibernate Application

1: Mapping file

2: Configuration File

3: Hibernate jars and mysql jars

4: Application

package model;

// Model JAVA Bean POJO Class


public class Employee {
private int id;
private String name;
private double salary;

public Employee() {
// TODO Auto-generated constructor stub
}

public Employee(int id, String name, double salary) {


super();
this.id = id;
this.name = name;
this.salary = salary;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" + salary +
"]";
}

---------------
hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>
<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

---------------------
employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-mapping>

<class name="model.Employee" table="emp">

<id name="id" column="eid"></id>


<property name="name" column="eName"></property>
<property name="salary" column="eSalary"></property>
</class>

</hibernate-mapping>

------------------------------

package app;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf=new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory=conf.buildSessionFactory();

// Step 3
Session session=factory.openSession();

// Step 4
Transaction tx=session.beginTransaction();

Employee emp=new Employee(11, "Rahul", 250000);

// Step 5
session.save(emp);

// Step 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Step 1
Configuration conf=new Configuration();

By Creating Configuration Object Hibernate environment started

conf.configure("hibernate.cfg.xml");

Internally Here “hibernate.cfg.xml” file loaded and here check wellness formatting
Of that xml .
These data inside file initialised into variable fields og configuration Object

// Step 2

SessionFactory factory=conf.buildSessionFactory();

// get all data of xml file and convert into single Object

SessionFactory is an interface

// Step 3
Session session=factory.openSession();

// In order to perform CRUD Operation we need Session Object


// we get this Object By calling Function openSession on SessionFactory
// When Session Object is Created then internally that session Object open a
connection with database

// Step 4
Transaction tx=session.beginTransaction();
// To perform non-select (insert update delete ) then we need Transaction Object
// for select Operation its not mandatory

Employee emp=new Employee(11, "Rahul", 250000);

// Step 5
session.save(emp);

// Step 6
tx.commit();
// If any exception Occurs while saving then transaction rollback.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<property name="hibernate.hbm2ddl.auto">update</property>

up
update
If the value is update then hibernate check whether table is exist or not
If it exist then it will add the data
If not then table is created and then add the data
Hibernate.hbm2ddl.auto
validate(default)
create
update
create-drop

validate

Here hibernate will check table is exist or not if exist then any operation data
If not table exist then throw exception

create
If property is create then first hibernate will drop table and the again created
and then any operation

create-drop
If first create a new table perform operation and then drop table

This property is used for performing unit testing

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

A dialect class generates SQl commands internally for hibernate based on


database

Hibernate has provided all dialect class for every databases

++++++++++++++++++++++++++++++++++++++++++++++++

Example To Read Data


package read;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class ReadData {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

Employee employee = (Employee) session.load(Employee.class, 11);

System.out.println(employee);

session.close();
factory.close();

System.out.println("Success Added");

++++++++++++++++++++++++++++++++++++++++++++++
We can read Object from from database by using
load(Student.class,11)
get(Student.class,11)

How Does the Load Method Work?

When we call load method internally it creates proxy object


And it set id to that object
Then it internally goes to database it will check id is present or not
In DB
If Id Found will get Proxy Object
If not then load method throw an exception which is
org.hibernate.ObjectNotFoundException:

Get method used lazy loading

get(Student.class,11)

Get method will immediately goes to database verifies id is present or not


If id is present it will return an Object from database

If id is not present in db then it will return null as Object

IMP
load method is used to lazily load an Object
get method is used to early load an Object

Update Data

1 By without reading from database


package update;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class UpdateData {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

Employee emp=new Employee();


emp.setId(11);
emp.setName("Ravi");
emp.setSalary(10000);

Transaction tx=session.beginTransaction();

session.update(emp);

tx.commit();

session.close();

System.out.println("Done");
}

2: By reading it from database and then update

package update;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class UpdateData {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

Employee e1=(Employee)session.get(Employee.class, 12);

if(e1!=null) {
e1.setName("Kalpesh");
e1.setSalary(250000);
Transaction tx=session.beginTransaction();

session.update(e1);

tx.commit();
}
else {
System.out.println("Id Not Found");

session.close();

System.out.println("Done");

Delete data

1: By without reading from database

package delete;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class DeleteData {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

Employee emp=new Employee();


emp.setId(11);

Transaction tx=session.beginTransaction();

session.delete(emp);

tx.commit();
session.close();

System.out.println("Data Deleted");
}

2: ByReading from Database

package delete;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class DeleteData {


public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();
Transaction tx = session.beginTransaction();

Employee emp = (Employee) session.get(Employee.class, 11);


if (emp != null) {

session.delete(emp);
tx.commit();
} else {
System.out.println("Not Existed Data In database");
}

session.close();

************************************************************************************************

JPA Annotation

@Entity
@Table
@Id
@Column

package model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// Model JAVA Bean POJO Class

@Entity
@Table(name = "emp")
public class Employee {
@Id
@Column(name = "eid")
private int id;
@Column(name = "eName")
private String name;
@Column(name = "eSalary")
private double salary;

public Employee() {
// TODO Auto-generated constructor stub
}

public Employee(int id, String name, double salary) {


super();
this.id = id;
this.name = name;
this.salary = salary;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" +
salary + "]";
}

++++++++++++++++++++++

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>
<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="model.Employee"/>
</session-factory>

</hibernate-configuration>

+++++++++++++++++++++++++++

package app;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import model.Employee;

public class App {


public static void main(String[] args) {

// Step 1
Configuration conf=new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory=conf.buildSessionFactory();

// Step 3
Session session=factory.openSession();

// Step 4
Transaction tx=session.beginTransaction();

Employee emp=new Employee(11, "Rahul", 250000);

// Step 5
session.save(emp);

// Step 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Instance States in Hibernate

In Hibernate there are 3 states of an instance Of POJO/Bean/Entity

1: Transient State
2: Persistent State
3:Detached State

1: Transient State

When we create an Object of POJO class or when we initialise that Object with
null value
Then Object is in Transient State

Product p=new Product();


// p Object is in Transient State

Product p=null;
// p Object is in Transient State

When an Object is in transient state and if we do some changes on that Object


Then this will not affect on to your database

2: Persistent State

The state of an Object is changed from transient to persistent when we call below
methods

save()
persist()
saveOrUpdate()
load()
get()
3:Detached State

When an Object is thrown out form session then state of an Object is convert
into detached state

session.close()
session.clear()
session.evict()

+++++++++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
@Id
private int bookId;
private String bookName;
private double bookPrice;

public Book() {
}

public Book(int bookId, String bookName, double bookPrice) {


super();
this.bookId = bookId;
this.bookName = bookName;
this.bookPrice = bookPrice;
}

public int getBookId() {


return bookId;
}

public void setBookId(int bookId) {


this.bookId = bookId;
}

public String getBookName() {


return bookName;
}

public void setBookName(String bookName) {


this.bookName = bookName;
}

public double getBookPrice() {


return bookPrice;
}

public void setBookPrice(double bookPrice) {


this.bookPrice = bookPrice;
}

@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ",
bookPrice=" + bookPrice + "]";
}

++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.dao;

import com.kalpesh.hibernate.model.Book;

public interface BookDAO {


void saveBook(Book book);
Book readBook(int bookId);

+++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kalpesh.hibernate.model.Book;
import com.kalpesh.hibernate.util.HibernateUtil;

public class BookDAOImpl implements BookDAO{

@Override
public void saveBook(Book book) {
SessionFactory factory=HibernateUtil.getSessionFactory();
Session session=factory.openSession();

Transaction tx=session.beginTransaction();

session.save(book);

tx.commit();

session.close();
System.out.println("Book Added....");

@Override
public Book readBook(int bookId) {
SessionFactory factory=HibernateUtil.getSessionFactory();
Session session=factory.openSession();
Book book=(Book)session.load(Book.class, bookId);

//session.close();
System.out.println("Reading Book From DB");
return book;
}

++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.dao;

public class BookDAOFactory {

public static BookDAO getInstance() {


return new BookDAOImpl();
}

++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static SessionFactory factory;

public static SessionFactory getSessionFactory() {


if(factory==null) {
return new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;

}
}

++++++++++++++++++++++++++++++++++++

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.kalpesh.hibernate.model.Book"/>
</session-factory>
</hibernate-configuration>

+++++++++++++++++++++++++++++++++++++++++++

package com.kalpesh.hibernate.app;

import com.kalpesh.hibernate.dao.BookDAO;
import com.kalpesh.hibernate.dao.BookDAOFactory;
import com.kalpesh.hibernate.model.Book;

public class App {

public static void main(String[] args) {

Book b1=new Book(14,"C#", 4444);

BookDAO dao=BookDAOFactory.getInstance();

dao.saveBook(b1);

System.out.println("---------------------------");

Book book=dao.readBook(12);

System.out.println("Book Id "+book.getBookId());
System.out.println("Book Name "+book.getBookName());
System.out.println("Book Price "+book.getBookPrice());

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Inheritance Mapping in Hibernate


Example
Table Per Class

Payment

package com.inheritance.model;

import java.util.Date;

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table(name = "Payment")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "PMODE",discriminatorType =
DiscriminatorType.STRING)
public class Payment {
@Id
private int payId;
private double payAmt;
private Date payDate;

public Payment() {
// TODO Auto-generated constructor stub
}

public int getPayId() {


return payId;
}

public void setPayId(int payId) {


this.payId = payId;
}

public double getPayAmt() {


return payAmt;
}

public void setPayAmt(double payAmt) {


this.payAmt = payAmt;
}

public Date getPayDate() {


return payDate;
}

public void setPayDate(Date payDate) {


this.payDate = payDate;
}

public Payment(int payId, double payAmt, Date payDate) {


super();
this.payId = payId;
this.payAmt = payAmt;
this.payDate = payDate;
}

@Override
public String toString() {
return "Payment [payId=" + payId + ", payAmt=" + payAmt + ",
payDate=" + payDate + "]";
}

++++++++++++++++++++++++++++++++
CreditCard
package com.inheritance.model;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value = "CC")
public class CreditCard extends Payment {

private int cardNum;


private String cardType;

public CreditCard() {
// TODO Auto-generated constructor stub
}

public CreditCard(int cardNum, String cardType) {


super();
this.cardNum = cardNum;
this.cardType = cardType;
}

public int getCardNum() {


return cardNum;
}
public void setCardNum(int cardNum) {
this.cardNum = cardNum;
}

public String getCardType() {


return cardType;
}

public void setCardType(String cardType) {


this.cardType = cardType;
}

@Override
public String toString() {
return "CreditCard [cardNum=" + cardNum + ", cardType=" +
cardType + "]";
}

+++++++++++++++++++++++++++++++++++++
Cheque

package com.inheritance.model;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value = "CH")
public class Cheque extends Payment {

private int chequeNo;


private String chequeType;

public Cheque() {
// TODO Auto-generated constructor stub
}

public Cheque(int chequeNo, String chequeType) {


super();
this.chequeNo = chequeNo;
this.chequeType = chequeType;
}

public int getChequeNo() {


return chequeNo;
}

public void setChequeNo(int chequeNo) {


this.chequeNo = chequeNo;
}

public String getChequeType() {


return chequeType;
}

public void setChequeType(String chequeType) {


this.chequeType = chequeType;
}

@Override
public String toString() {
return "Cheque [chequeNo=" + chequeNo + ", chequeType=" +
chequeType + "]";
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++
DAO

package com.inheritance.dao;
import com.inheritance.model.Cheque;
import com.inheritance.model.CreditCard;

public interface PaymentDAO {

void saveCard(CreditCard card);

void saveCheque(Cheque cheque);

++++++++++++++++++++++

package com.inheritance.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.inheritance.model.Cheque;
import com.inheritance.model.CreditCard;
import com.inheritance.util.HibernateUtility;

public class PaymentDAOImpl implements PaymentDAO{

@Override
public void saveCard(CreditCard card) {

SessionFactory factory=HibernateUtility.getSessionFactory();

Session session=factory.openSession();

Transaction tx=session.beginTransaction();

session.save(card);

tx.commit();

session.close();
System.out.println("Credit Card Transaction Added Succes ! ! !");
}

@Override
public void saveCheque(Cheque cheque) {

SessionFactory factory=HibernateUtility.getSessionFactory();

Session session=factory.openSession();

Transaction tx=session.beginTransaction();

session.save(cheque);

tx.commit();

session.close();
System.out.println("cheque Transaction Added Succes ! ! !");

++++++++++++++++++++++++++++++++++++++
package com.inheritance.dao;

public class PaymentDAOFactory {

public static PaymentDAO getInstance() {

return new PaymentDAOImpl(); // savecard savecheqye


}
}

+++++++++++++++++++++++++++++++++++++++

HibernateUtility
package com.inheritance.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {

private static SessionFactory factory;

public synchronized static SessionFactory getSessionFactory() {


if (factory == null) {
return new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;

++++++++++++++++++++++++++++++++++++++++++

Configuration file

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.inheritance.model.Payment"/>
<mapping class="com.inheritance.model.CreditCard"/>
<mapping class="com.inheritance.model.Cheque"/>
</session-factory>

</hibernate-configuration>

+++++++++++++++++++++++++++++++++++++++++++++++++++++++
APP

package com.inheritance.app;

import java.util.Date;

import com.inheritance.dao.PaymentDAO;
import com.inheritance.dao.PaymentDAOFactory;
import com.inheritance.model.Cheque;
import com.inheritance.model.CreditCard;

public class App {

public static void main(String[] args) {

PaymentDAO dao=PaymentDAOFactory.getInstance();

CreditCard card=new CreditCard();


card.setPayId(1111);
card.setPayAmt(10000);
card.setPayDate(new Date(2022, 8, 25));
card.setCardNum(11111111);
card.setCardType("MAESTRO");

dao.saveCard(card);

System.out.println("----------CARD SAVED------------------");

Cheque ch=new Cheque();


ch.setPayId(2222);
ch.setPayAmt(20000);
ch.setPayDate(new Date(2022,7,25));
ch.setChequeNo(22222222);
ch.setChequeType("Order");
dao.saveCheque(ch);

System.out.println("-------------CHEQUE
SAVED--------------------");

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++

In hibernate application if there are multiple POJO classes and if they have
common properties then to get reusability will use Inheritance

Hibernate has provided 3 Inheritance Strategies , to map the classes of hierarchy


to database tables.
1: Table Per Class

2: Table Per Concrete Class

3: Table Per Subclass

# We need to choose table per class strategy , if we want to map all the classes
in Single Table

# If We need to map each Concrete class to separate table of database then we


need to use table per Concrete Class

abstract Payment
|
|
—-----------------
| |
| |
CreditCard Cheque —--> CONCRETE CLASSES

So Here CreditCard And Cheque Table Created

# When we want to map each class of hierarchy to separate table then we need
to select table per subclass

abstract Payment [Payment Table Created]


|
|
—-----------------
| |
| |
CreditCard Cheque → Both CreditCard and Cheque table Created
Table Per Concrete Class

Ex-

Payment

package com.concret.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Payment {
@Id
private int payId;
private double payAmt;
private Date payDate;

public Payment() {
// TODO Auto-generated constructor stub
}

public int getPayId() {


return payId;
}

public void setPayId(int payId) {


this.payId = payId;
}
public double getPayAmt() {
return payAmt;
}

public void setPayAmt(double payAmt) {


this.payAmt = payAmt;
}

public Date getPayDate() {


return payDate;
}

public void setPayDate(Date payDate) {


this.payDate = payDate;
}

public Payment(int payId, double payAmt, Date payDate) {


super();
this.payId = payId;
this.payAmt = payAmt;
this.payDate = payDate;
}

@Override
public String toString() {
return "Payment [payId=" + payId + ", payAmt=" + payAmt + ",
payDate=" + payDate + "]";
}

+++++++++++++++++++++++++++++++++++++

package com.concret.model;

import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "Cheque")
public class Cheque extends Payment {

private int chequeNo;


private String chequeType;

public Cheque() {
// TODO Auto-generated constructor stub
}

public Cheque(int chequeNo, String chequeType) {


super();
this.chequeNo = chequeNo;
this.chequeType = chequeType;
}

public int getChequeNo() {


return chequeNo;
}

public void setChequeNo(int chequeNo) {


this.chequeNo = chequeNo;
}

public String getChequeType() {


return chequeType;
}

public void setChequeType(String chequeType) {


this.chequeType = chequeType;
}

@Override
public String toString() {
return "Cheque [chequeNo=" + chequeNo + ", chequeType=" +
chequeType + "]";
}
}

++++++++++++++++++++++++++++++++++++++++

package com.concret.model;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "credit")
public class CreditCard extends Payment {

private int cardNum;


private String cardType;

public CreditCard() {
// TODO Auto-generated constructor stub
}

public CreditCard(int cardNum, String cardType) {


super();
this.cardNum = cardNum;
this.cardType = cardType;
}

public int getCardNum() {


return cardNum;
}

public void setCardNum(int cardNum) {


this.cardNum = cardNum;
}

public String getCardType() {


return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}

@Override
public String toString() {
return "CreditCard [cardNum=" + cardNum + ", cardType=" +
cardType + "]";
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

package com.concret.utility;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// Singleton Design Pattern
public class HibernateUtility {

private static SessionFactory factory;

public synchronized static SessionFactory getSessionFactory() {


if (factory == null) {
return new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;

++++++++++++++++++++++++++++++++++++

package com.concret.dao;
import com.concret.model.Cheque;
import com.concret.model.CreditCard;

public interface PaymentDAO {

void saveCard(CreditCard card);

void saveCheque(Cheque cheque);

+++++++++++++++++++++++++++++++++++++++

package com.concret.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.concret.model.Cheque;
import com.concret.model.CreditCard;
import com.concret.utility.HibernateUtility;

public class PaymentDAOImpl implements PaymentDAO{

@Override
public void saveCard(CreditCard card) {

SessionFactory factory=HibernateUtility.getSessionFactory();

Session session=factory.openSession();

Transaction tx=session.beginTransaction();

session.save(card);

tx.commit();

session.close();
System.out.println("Credit Card Transaction Added Succes ! ! !");

@Override
public void saveCheque(Cheque cheque) {
SessionFactory factory=HibernateUtility.getSessionFactory();

Session session=factory.openSession();

Transaction tx=session.beginTransaction();

session.save(cheque);

tx.commit();

session.close();
System.out.println("cheque Transaction Added Succes ! ! !");

+++++++++++++++++++++++++++++++++++++

package com.concret.dao;

public class PaymentDAOFactory {

public static PaymentDAO getInstance() {

return new PaymentDAOImpl(); // savecard savecheqye


}
}

+++++++++++++++++++++++++++++++++++++++++

package com.concret.app;

import java.util.Date;

import com.concret.dao.PaymentDAO;
import com.concret.dao.PaymentDAOFactory;
import com.concret.model.Cheque;
import com.concret.model.CreditCard;

public class App {


public static void main(String[] args) {

PaymentDAO dao=PaymentDAOFactory.getInstance();

CreditCard card=new CreditCard();


card.setPayId(1111);
card.setPayAmt(10000);
card.setPayDate(new Date(2022, 8, 25));
card.setCardNum(11111111);
card.setCardType("MAESTRO");

dao.saveCard(card);

System.out.println("----------CARD SAVED------------------");

Cheque ch=new Cheque();


ch.setPayId(2222);
ch.setPayAmt(20000);
ch.setPayDate(new Date(2022,7,25));
ch.setChequeNo(22222222);
ch.setChequeType("Order");
dao.saveCheque(ch);

System.out.println("-------------CHEQUE
SAVED--------------------");

+++++++++++++++++++++++++++++++++++++++++++++++++++

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpsept2</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.concret.model.Payment"/>
<mapping class="com.concret.model.CreditCard"/>
<mapping class="com.concret.model.Cheque"/>
</session-factory>

</hibernate-configuration>

3 Table Per Subclass [HW]


—---------------------

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name = "payment")
public abstract class Payment {
@Id
@Column(name=”pid”)
private int payId;
private double payAmt;
private Date payDate;

@Entity
@Table(name = "credit")
@PrimaryKeyJoinColumn(name=”pid”)
public class CreditCard extends Payment {

private int cardNum;


private String cardType;

@Entity
@Table(name = "Cheque")
@PrimaryKeyJoinColumn(name=”pid”)
public class Cheque extends Payment {

private int chequeNo;


private String chequeType;

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++

Component Mapping
_______________

+ Component Mapping is used when there is has-a relationship between POJO


classes
+ In Component Mapping , Object of a class will be stored as a value of
another class Object
+ In “has-a” relationship , we call the first class as a dependent Object and
second class as dependency
+ If we want to save a dependant Object along with its dependency Object in
a single table of database then we need to use component Mapping

Here in the below example we are saving employee Object along with Address
Object

And We use Annotation


@Entity
@Table(name = "empdetails")
public class Employee {
@Id
private int id;
private String name;

@Embedded
private Address address;

@Embeddable
public class Address {
private int houseNo;
private String street;
private String city;

Ex

Model Class

package com.model;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "empdetails")
public class Employee {
@Id
private int id;
private String name;

@Embedded
private Address addres;

public Employee() {
// TODO Auto-generated constructor stub
}

public Employee(int id, String name, Address addres) {


super();
this.id = id;
this.name = name;
this.addres = addres;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", addres=" +
addres + "]";
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public Address getAddres() {
return addres;
}

public void setAddres(Address addres) {


this.addres = addres;
}

+++++++++++++++++
package com.model;

import javax.persistence.Embeddable;

@Embeddable
public class Address {
private int houseNo;
private String street;
private String city;

public Address() {
// TODO Auto-generated constructor stub
}

public Address(int houseNo, String street, String city) {


super();
this.houseNo = houseNo;
this.street = street;
this.city = city;
}

public int getHouseNo() {


return houseNo;
}
public void setHouseNo(int houseNo) {
this.houseNo = houseNo;
}

public String getStreet() {


return street;
}

public void setStreet(String street) {


this.street = street;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

@Override
public String toString() {
return "Address [houseNo=" + houseNo + ", street=" + street + ",
city=" + city + "]";
}

+++++++++++++++++++++++++

++++++++++++++++++
<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>
<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.model.Employee"/>
<mapping class="com.model.Address"/>
</session-factory>

</hibernate-configuration>

++++++++++++++++++++++++++++++++

package com.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {


private static SessionFactory factory;

public static SessionFactory getSessionFactory() {


if(factory==null) {
return new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;

}
}

+++++++++++++++++++++++++++++++++++++++

package com.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.model.Employee;
import com.util.HibernateUtil;

public class EmployeeDAO {

public void saveEmp(Employee emp)


{
SessionFactory factory=HibernateUtil.getSessionFactory();

Session sesion=factory.openSession();

Transaction tx=sesion.beginTransaction();

sesion.save(emp);

tx.commit();
factory.close();
System.out.println("Inser data Success !!!!");
}
}

++++++++++++++++++++++++++++++++++

App

package com.app;

import com.dao.EmployeeDAO;
import com.model.Address;
import com.model.Employee;

public class App {

public static void main(String[] args) {

Address add=new Address(11, "FC Road", "PUNE");


Employee employee=new Employee(222,"Sagar",add);

EmployeeDAO dao=new EmployeeDAO();


dao.saveEmp(employee);

System.out.println("*****************");
}
}

++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++

Bulk Operation
+By Calling save(), update(), delete(),load() etc
We can perform crud on operation on single Object.

+ If we want to work on multiple Objects at a time we use bulk operation


technique of Hibernate

1: HQL

2: Criteria

+ HQL is same like SQL but it doesnt depend on database

+ To construct SQL quries , we use variable name in place of column name

className on place of table name

SQL: select * from empdetails;

HQL: from Employee e;

SQL : select name,city from empdetails;

When it comes to read partial entity HQL used SELECT

HQL : select e.name, e.city from Employee e;

++++++++++++++++++++++++++++++++++++++++++++++
Hibernate HQL

Model Class
package com.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* @author Kalpesh
*
*/
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String name;
private double marks;

public Student() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getMarks() {


return marks;
}

public void setMarks(double marks) {


this.marks = marks;
}

@Override
public String toString() {
return "Stiudent [id=" + id + ", name=" + name + ", marks=" + marks
+ "] \n";
}

++++++++++++++++++++

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.model.Student"/>
</session-factory>

</hibernate-configuration>

+++++++++++++++++++++++++++++++++

App

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf=new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory=conf.buildSessionFactory();

// Step 3
Session session=factory.openSession();

// Step 4
Transaction tx=session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

String sql="from Student e";


Query query=session.createQuery(sql);

List list=query.list();

Iterator iterator=list.iterator();

while(iterator.hasNext()) {
Student student=(Student)iterator.next();
System.out.println(student);

// Strp 6
tx.commit();

session.close();
factory.close();
System.out.println("Success Added");

+++++++++++++++++++++++++++++++++++++++++++++

SQL: select name,marks from student;

HQL:

[Partial Entity ]

select s.name,s.marks from student s;

++++++++++++++

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.model.Student;

public class App {


public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

String sql = "select s.name,s.marks from Student s";


Query query = session.createQuery(sql);

List list = query.list();

Iterator iterator = list.iterator();

while (iterator.hasNext()) {
Object ob[]=(Object [])iterator.next();

System.out.println(" "+ob[0]+" "+ob[1]);

// Strp 6
tx.commit();
session.close();
factory.close();

System.out.println("Success Added");

+++++++++++++++++++++++++++++++++++++

Only To Read Single Column

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");
// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

String sql = "select s.name from Student s";


Query query = session.createQuery(sql);

List list = query.list();

Iterator iterator = list.iterator();

while (iterator.hasNext()) {
System.out.println(iterator.next());

// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

}
++++++++++++++++++++++++++++++++++++++++++

SQL --> update student set name='Roy' where id=3;

HQL --> update Student s set s.name='Roy' where id=3;

++++++++++++++++++++++++++++++++++++++++++++++++

Criteria
----------------------

Only For Select Operation

Query tunning

Criteria criteria=session.createCriteria("Entity")

List list=critaria.list();

Ex No 1:

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

Criteria criteria = session.createCriteria(Student.class);

criteria.add(Restrictions.eq("marks", 55.0));

List list=criteria.list();

Iterator itr=list.iterator();

while(itr.hasNext()) {
System.out.println(itr.next());
}

// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

++++++++++++++++++++++++

To Get 2 nd to 5 th record

[Range records]

++++++++++++++++++

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

Criteria criteria = session.createCriteria(Student.class);

criteria.setFirstResult(2);
criteria.setMaxResults(5);

List list=criteria.list();

Iterator itr=list.iterator();

while(itr.hasNext()) {
System.out.println(itr.next());
}
// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

+++++++++++++++++++++++++++++++++++++++++++++++

Records in Ascending Order

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.model.Student;

public class App {

public static void main(String[] args) {


// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

Criteria criteria = session.createCriteria(Student.class);

criteria.addOrder(Order.asc("marks"));
List list=criteria.list();

Iterator itr=list.iterator();

while(itr.hasNext()) {
System.out.println(itr.next());
}

// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

++++++++++++++++++++++++++++++++

To Read Partial Entity

package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();

// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

Criteria criteria = session.createCriteria(Student.class);

criteria.setProjection(Projections.property("name"));
List list=criteria.list();

Iterator itr=list.iterator();

while(itr.hasNext()) {
System.out.println(itr.next());
}

// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");
}

+++++++++++++++++++++++++++++
package com.app;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.model.Student;

public class App {

public static void main(String[] args) {

// Step 1
Configuration conf = new Configuration();

conf.configure("hibernate.cfg.xml");

// Step 2

SessionFactory factory = conf.buildSessionFactory();

// Step 3
Session session = factory.openSession();
// Step 4
Transaction tx = session.beginTransaction();
/*
* Student s1=new Student(); //s1.setId(101); s1.setName("jyoti");
* s1.setMarks(89);
*
* // Step 5 session.save(s1);
*/

Criteria criteria = session.createCriteria(Student.class);

criteria.setProjection(Projections.property("name"));
List list = criteria.list();

Iterator itr = list.iterator();

while (itr.hasNext()) {
System.out.println(itr.next());
}

System.out.println("---------------------------------------------");

Criteria criteria2 = session.createCriteria(Student.class);


Projection p1 = Projections.rowCount();
Projection p2 = Projections.sum("marks");

ProjectionList plist = Projections.projectionList();


plist.add(p1);
plist.add(p2);

criteria2.setProjection(plist);

List list1 = criteria2.list();

for (int i = 0; i < list1.size(); i++) {


// System.out.println(list1.get(i));
Object[] arr = (Object[]) list1.get(i);
System.out.println("Row " + arr[0] + " SUM " + arr[1]);
}

// Strp 6
tx.commit();

session.close();
factory.close();

System.out.println("Success Added");

+++++++++++++++++++++++++++++

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="DateServlet" method="get">

<label for="birthday">Birthday:</label> <input type="date"


id="birthday" name="birthday">

<input type="submit" value="OK">


</form>
</body>
</html>

++++++++++++++

package p1;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class DateServlet
*/
@WebServlet("/DateServlet")
public class DateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/datel", "root", "root");

String date = request.getParameter("birthday");


System.out.println("Date in String " + date);

LocalDate lde = LocalDate.parse(date);

String query = "insert into dd values(?)";

PreparedStatement ps = con.prepareStatement(query);
ps.setObject(1, lde);

int i = ps.executeUpdate();

if (i >= 1) {
System.out.println("Done");
}

} catch (Exception e) {
System.out.println(e);
}

+++++++++++++++++++++++++++++++++++++++++++++++

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="EmployeeServlet" method="get">

Id:<input type="text" name="id"><br> Name: <input


type="text" name="uname"> <br> Salary : <input
type="text" name="salary"><br> <input type="submit"
value="OK">

</form>

</body>
</html>

++++++++++++++++++++++++++++++++++
package com.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "empcrud")
public class Employee {

@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private double salary;

public Employee() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public double getSalary() {
return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" +
salary + "]";
}

+++++++++++++++++++++++++++++++++

package com.dao;

import com.model.Employee;

public interface EmployeeDAO {

void saveEmployee(Employee emp);

++++++++++++++++++++

package com.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.hibernate.util.HibernateUtil;
import com.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {

@Override
public void saveEmployee(Employee emp) {

SessionFactory factory = HibernateUtil.getSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();
session.save(emp);

tx.commit();

System.out.println("Save Data");
session.close();

++++++++++++++++++++++++++++++++
package com.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {


private static SessionFactory factory;

public static synchronized SessionFactory getSessionFactory() {


if(factory==null) {
return new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;

}
}

+++++++++++++++++++++++++++++++
package com.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.EmployeeDAO;
import com.dao.EmployeeDAOImpl;
import com.model.Employee;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

EmployeeDAO dao;

@Override
public void init() throws ServletException {
dao = new EmployeeDAOImpl();
}
public EmployeeServlet() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

int id=Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("uname");
double salary = Double.parseDouble(request.getParameter("salary"));

Employee employee = new Employee();


employee.setId(id);
employee.setName(name);
employee.setSalary(salary);

dao.saveEmployee(employee);

//we cab redirect Page


}

++++++++++++++++++++++++++++++

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>

<session-factory>

<!-- Connection Properties -->

<property name="hibernate.connection.driver_class"> com.mysql.cj.jdbc.Driver


</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/itpseptemp</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Hibernate Properties -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping resource -->

<mapping class="com.model.Employee"/>
</session-factory>

</hibernate-configuration>

++++++++++++++++++++++++++++++++++++++++++++++++

ADDED POINT

package com.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.EmployeeDAO;
import com.dao.EmployeeDAOImpl;

/**
* Servlet implementation class DeleteEmploee
*/
@WebServlet("/DeleteEmployee")
public class DeleteEmployee extends HttpServlet {

EmployeeDAO dao;
private static final long serialVersionUID = 1L;

@Override
public void init() throws ServletException {
dao=new EmployeeDAOImpl();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

int id = Integer.parseInt(request.getParameter("id"));

dao.deleteEmployeeById(id);

out.print("<h1> "+ "Deleted "+"</h1>");

out.print("<a href='Servelet?id='"+id+"</a?");

+++++++++++++++++++++++++++++++++
package com.dao;

import java.util.List;

import com.model.Employee;

public interface EmployeeDAO {

void saveEmployee(Employee emp);

void deleteEmployeeById(int id);

List<Employee> findAllEmployess();

package com.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.hibernate.util.HibernateUtil;
import com.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {

@Override
public void saveEmployee(Employee emp) {
SessionFactory factory = HibernateUtil.getSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();
session.save(emp);

tx.commit();

System.out.println("Save Data");
session.close();

public void deleteEmployeeById(int id) {

SessionFactory factory = HibernateUtil.getSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();

Employee employee =(Employee) session.get(Employee.class, id);

System.out.println(employee);
session.delete(employee);
tx.commit();
System.out.println("Delete Data");
session.close();

@Override
public List<Employee> findAllEmployess() {

SessionFactory factory = HibernateUtil.getSessionFactory();

Session session = factory.openSession();


Criteria criteria=session.createCriteria(Employee.class);

List<Employee> empList=criteria.list();

return empList;
}

+++++++++++++++++++++++++++++++++++++++++++++

package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.EmployeeDAO;
import com.dao.EmployeeDAOImpl;
import com.model.Employee;

/**
* Servlet implementation class ReadEmployee
*/
@WebServlet("/ReadEmployee")
public class ReadEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
EmployeeDAO dao;
@Override
public void init() throws ServletException {
dao = new EmployeeDAOImpl();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/htmml");
PrintWriter out=response.getWriter();

List<Employee>list=dao.findAllEmployess();

request.setAttribute("list", list);

request.getRequestDispatcher("displayEmployees.jsp").forward(request,
response);
}

++++++++++++++++++++++++++++++++++++++++++++++++++

You might also like