Hibernate JuneJuly
Hibernate JuneJuly
Hibernate JuneJuly
https://jar-download.com/artifacts/org.hibernate/hibernate-core
perspective
jdk 1.8
Eclipse
Mysql 8
Apache Tomcat
Hibernate
----------------------------------
// 2 Step
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName","root","ro
ot");
// 3 Step
Statement stmt=con.createStaement()
Step 5
// Loop
// Boiler Plate Code --> Means every time we are going write the same code
+++++++++++++++++++++++++++
+++++++++++++++++++++++++++
1: Invasive Framework
2: Non-Invasive Framework
A developer need not to be extends or implements something
Ex - Hibernate , Spring
+ Hibernate
----------------------
Ex
class A{
Ex
A class which does not exceeds core java api called as POJO class
B(){ }
public void setX(int x) {}
public int getX() { return x;}
----------
class A{
class C{
-------------------------------------------
Hibernate Application
1: Mapping file
2: Configuration File
4: Application
package model;
public Employee() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" + salary +
"]";
}
---------------
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
---------------------
employee.hbm.xml
<hibernate-mapping>
</hibernate-mapping>
------------------------------
package app;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// 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();
// Step 5
session.save(emp);
// Step 6
tx.commit();
session.close();
factory.close();
System.out.println("Success Added");
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Step 1
Configuration conf=new Configuration();
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();
// Step 4
Transaction tx=session.beginTransaction();
// To perform non-select (insert update delete ) then we need Transaction Object
// for select Operation its not mandatory
// Step 5
session.save(emp);
// Step 6
tx.commit();
// If any exception Occurs while saving then transaction rollback.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<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
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
++++++++++++++++++++++++++++++++++++++++++++++++
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// Step 3
Session session = factory.openSession();
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)
get(Student.class,11)
IMP
load method is used to lazily load an Object
get method is used to early load an Object
Update Data
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// Step 3
Session session = factory.openSession();
Transaction tx=session.beginTransaction();
session.update(emp);
tx.commit();
session.close();
System.out.println("Done");
}
package update;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// Step 3
Session session = factory.openSession();
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
package delete;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// Step 3
Session session = factory.openSession();
Transaction tx=session.beginTransaction();
session.delete(emp);
tx.commit();
session.close();
System.out.println("Data Deleted");
}
package delete;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Employee;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// Step 3
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
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;
@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
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" +
salary + "]";
}
++++++++++++++++++++++
<hibernate-configuration>
<session-factory>
<!-- Connection Properties -->
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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;
// 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();
// Step 5
session.save(emp);
// Step 6
tx.commit();
session.close();
factory.close();
System.out.println("Success Added");
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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=null;
// p Object is in Transient State
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() {
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ",
bookPrice=" + bookPrice + "]";
}
++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.dao;
import com.kalpesh.hibernate.model.Book;
+++++++++++++++++++++++++++++++++++
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;
@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;
++++++++++++++++++++++++++++++++++++++++++
package com.kalpesh.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
}
}
++++++++++++++++++++++++++++++++++++
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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;
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());
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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
}
@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 {
public CreditCard() {
// TODO Auto-generated constructor stub
}
@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 {
public Cheque() {
// TODO Auto-generated constructor stub
}
@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;
++++++++++++++++++++++
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;
@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;
+++++++++++++++++++++++++++++++++++++++
HibernateUtility
package com.inheritance.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
++++++++++++++++++++++++++++++++++++++++++
Configuration file
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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;
PaymentDAO dao=PaymentDAOFactory.getInstance();
dao.saveCard(card);
System.out.println("----------CARD SAVED------------------");
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
# We need to choose table per class strategy , if we want to map all the classes
in Single Table
abstract Payment
|
|
—-----------------
| |
| |
CreditCard Cheque —--> CONCRETE CLASSES
# When we want to map each class of hierarchy to separate table then we need
to select table per subclass
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
}
@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 {
public Cheque() {
// TODO Auto-generated constructor stub
}
@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 {
public CreditCard() {
// TODO Auto-generated constructor stub
}
@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 {
++++++++++++++++++++++++++++++++++++
package com.concret.dao;
import com.concret.model.Cheque;
import com.concret.model.CreditCard;
+++++++++++++++++++++++++++++++++++++++
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;
@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;
+++++++++++++++++++++++++++++++++++++++++
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;
PaymentDAO dao=PaymentDAOFactory.getInstance();
dao.saveCard(card);
System.out.println("----------CARD SAVED------------------");
System.out.println("-------------CHEQUE
SAVED--------------------");
+++++++++++++++++++++++++++++++++++++++++++++++++++
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.concret.model.Payment"/>
<mapping class="com.concret.model.CreditCard"/>
<mapping class="com.concret.model.Cheque"/>
</session-factory>
</hibernate-configuration>
@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 {
@Entity
@Table(name = "Cheque")
@PrimaryKeyJoinColumn(name=”pid”)
public class Cheque extends Payment {
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++
Component Mapping
_______________
Here in the below example we are saving employee Object along with Address
Object
@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
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", 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
}
@Override
public String toString() {
return "Address [houseNo=" + houseNo + ", street=" + street + ",
city=" + city + "]";
}
+++++++++++++++++++++++++
++++++++++++++++++
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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;
}
}
+++++++++++++++++++++++++++++++++++++++
package com.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.model.Employee;
import com.util.HibernateUtil;
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;
System.out.println("*****************");
}
}
++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++
Bulk Operation
+By Calling save(), update(), delete(),load() etc
We can perform crud on operation on single Object.
1: HQL
2: Criteria
++++++++++++++++++++++++++++++++++++++++++++++
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
}
@Override
public String toString() {
return "Stiudent [id=" + id + ", name=" + name + ", marks=" + marks
+ "] \n";
}
++++++++++++++++++++
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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;
// 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);
*/
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");
+++++++++++++++++++++++++++++++++++++++++++++
HQL:
[Partial Entity ]
++++++++++++++
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;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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);
*/
while (iterator.hasNext()) {
Object ob[]=(Object [])iterator.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.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.model.Student;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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);
*/
while (iterator.hasNext()) {
System.out.println(iterator.next());
// Strp 6
tx.commit();
session.close();
factory.close();
System.out.println("Success Added");
}
++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++
Criteria
----------------------
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;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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.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;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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.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");
+++++++++++++++++++++++++++++++++++++++++++++++
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;
conf.configure("hibernate.cfg.xml");
// Step 2
// 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.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");
++++++++++++++++++++++++++++++++
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;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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.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;
// Step 1
Configuration conf = new Configuration();
conf.configure("hibernate.cfg.xml");
// Step 2
// 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.setProjection(Projections.property("name"));
List list = criteria.list();
while (itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println("---------------------------------------------");
criteria2.setProjection(plist);
// Strp 6
tx.commit();
session.close();
factory.close();
System.out.println("Success Added");
+++++++++++++++++++++++++++++
++++++++++++++
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;
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>
</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
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" +
salary + "]";
}
+++++++++++++++++++++++++++++++++
package com.dao;
import com.model.Employee;
++++++++++++++++++++
package com.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.hibernate.util.HibernateUtil;
import com.model.Employee;
@Override
public void saveEmployee(Employee emp) {
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;
}
}
+++++++++++++++++++++++++++++++
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
}
int id=Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("uname");
double salary = Double.parseDouble(request.getParameter("salary"));
dao.saveEmployee(employee);
++++++++++++++++++++++++++++++
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<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();
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
dao.deleteEmployeeById(id);
out.print("<a href='Servelet?id='"+id+"</a?");
+++++++++++++++++++++++++++++++++
package com.dao;
import java.util.List;
import com.model.Employee;
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;
@Override
public void saveEmployee(Employee emp) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Transaction tx = session.beginTransaction();
session.save(emp);
tx.commit();
System.out.println("Save Data");
session.close();
Transaction tx = session.beginTransaction();
System.out.println(employee);
session.delete(employee);
tx.commit();
System.out.println("Delete Data");
session.close();
@Override
public List<Employee> findAllEmployess() {
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();
}
response.setContentType("text/htmml");
PrintWriter out=response.getWriter();
List<Employee>list=dao.findAllEmployess();
request.setAttribute("list", list);
request.getRequestDispatcher("displayEmployees.jsp").forward(request,
response);
}
++++++++++++++++++++++++++++++++++++++++++++++++++