Hibernate Class Notes
Hibernate Class Notes
EntityManagerFactory
emf=Persistence.createEntityManagerFactory("studentUnit");
if(student == null){
System.out.println("Student does not exist..");
}
else
{
em.getTransaction().begin();
student.setMarks(student.getMarks()+marks);
em.getTransaction().commit();
System.out.println("Marks is graced...");
}
em.close();
System.out.println("done");
--in the above application we didn't call any update method, we just change the
state of the persistence/entity obj
inside the transactional area, at the end of the tx , ORM engine will generate the
update sql.
--this is known as the ORM s/w maintaining synchronization bt entity obj and the db
table records.
--we have a method called merge() inside the EntityManager obj to update a record
also.
3.detached state
--if we create a object of persistence class and this class is not attached with
the EM obj, then
this stage is known as new state/transient state
2.persistence state:-
-------------------------
--if a persistence class obj or Entity obj is associated with EM obj, then this obj
will be in persistence state.
ex:-
when we call a persist(-) method by supplying Student entity obj then at time
student obj will be in persistence state
or
when we call find() method and this method returns the Student obj, then that obj
will also be in persistence state.
Note:- when an entity class obj is in persisitence state ,it is in-sync with the DB
table ,i.e
any change made on that obj inside the tx area will reflect to the table
automatically.
ex:-
em.getTransaction().begin();
em.persist(s); // here it is in the persistence state
s.setMarks(900);
em.getTransaction().commit();
detached state:-
-------------------
--when we call close() method or call clear() method on the EM obj, then all the
associated entity obj will be in detached state.
--in this stage the entity objs will not be in-sync with the table.
Note:- we have a merge() method in EM obj, when we call this method by supplying
any detached object then that detached object will bring back in the persistence
state.
ex:-
Main.java:-
-------------
EntityManagerFactory
emf=Persistence.createEntityManagerFactory("studentUnit");
em.getTransaction().begin();
s.setMarks(500);
em.getTransaction().commit();
System.out.println("done");
}
}
em.persist()
em.find()------------>persistence state-----------em.close(), em.clear()---------
>detached state---->em.merge()--->persistence state
Note:- to see the ORM tool(HB) generated sql queries on the console add the
following property inside the persistence.xml
to create or update the table according to the entity class mapping information:-
create :- drop the existing table then create a fresh new table and insert the
record.
update :- if table is not there then create a new table, and if table is already
there it will perform insert operation only in the existing table.
@Entity :- to make a java bean class as entity , i.e to map with a table
Generators in JPA:-
----------------------
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int roll;
Note:- if we use this @GeneratedValue annoation then we are not allowed to give the
roll explicitly while inserting a record.
--so we should create a object by using zero argument constrcutor and set the each
value by calling setter method.
AUTO :- internally underlaying ORM s/w creates a secquence or a table called
"hibernate_sequence" to maintain the Id value.
EMUtil.java:-
----------------
static{
emf=Persistence.createEntityManagerFactory("account-unit");
}
return emf.createEntityManager();
}
}
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int accno;
private String name;
private int balance;
public Account() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Account [accno=" + accno + ", name=" + name + ", balance="
+ balance + "]";
}
AccountDao.java:-(interface)
--------------------
}
AccountDaoImpl.java:-
---------------------------
@Override
public boolean createAccount(Account account) {
em.getTransaction().begin();
em.persist(account);
flag=true;
em.getTransaction().commit();
em.close();
return flag;
}
@Override
public boolean deleteAccount(int accno) {
boolean flag=false;
if(acc != null){
em.getTransaction().begin();
em.remove(acc);
flag=true;
em.getTransaction().commit();
}
em.close();
return flag;
}
@Override
public boolean updateAccount(Account account) {
boolean flag=false;
em.merge(account);
flag=true;
em.getTransaction().commit();
em.close();
return flag;
@Override
public Account findAccount(int accno) {
/*Account account=null;
EntityManager em=EMUtil.provideEntityManager();
return account;*/
}
}
persistence.xml:-
--------------------
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/ratandb"/>
</properties>
</persistence-unit>
</persistence>
DepositUseCase.java:-
----------------------------
boolean f= dao.createAccount(acc1);
if(f)
System.out.println("Account created..");
else
System.out.println("Not created...");*/
if(acc == null)
System.out.println("Account does not exist..");
else{
acc.setBalance(acc.getBalance()+amt);
boolean f =dao.updateAccount(acc);
if(f)
System.out.println("Deposited Sucessfully...");
else
System.out.println("Technical Error .....");
}
}
WithdrawUseCase.java:-
-----------------------------
if(acc == null)
System.out.println("Account does not exist..");
else{
acc.setBalance(acc.getBalance()-amt);
boolean f=dao.updateAccount(acc);
if(f)
System.out.println("please collect the cash...");
else
System.out.println("Technical Error...");
}else
System.out.println("Insufficient Amount..");
}
}
***********************************************************************************
******************************************************************
persist();
find()
merge();
4.to access Entity obj we can not specify some extra condition.
--to overcome the above limitation JPA has provided JPQL (java persistence query
language).
--the way we express the condition to perform the CRUD operation is almost
simmilar.
--the name of the class and its variables are case sensitive.
sql> select name,marks from student; (name and marks are the column name and
student is the table name)
jpql> select name,marks from Student; (here name and marks are the variables
defined inside the Student class)
ex:-
Query q =em.createQuery("JPQL query");
step 3:- bind the values if any placeholders are used.(here we have 2 types of
place holders 1.positional 2.named placeholders).
step 4:- submit the jpql query by calling either one of the following methods:-
for insert/update/delete :-
ex:-
in sql :-
in jpql:-
JPQLMain.java:-
-------------------
for(Account acc:list){
System.out.println(acc);
}
}
}
search on non-pk:-
-----------------------
for(Account acc:list){
System.out.println(acc);
}
}
System.out.println(acc);
--if the above query will return more that one result then it will throw a runtime
exception
in order to avoid the downcasting problem we should use TypedQuery instead of Query
obj.
ex:-
bulk update:-
------------------
Query q= em.createQuery(jpql);
em.getTransaction().begin();
int x= q.executeUpdate();
em.getTransaction().commit();
Query q= em.createQuery(jpql);
q.setParameter(5, 1000);
q.setParameter(6, "Manoj");
em.getTransaction().begin();
int x=q.executeUpdate();
em.getTransaction().commit();
Query q= em.createQuery(jpql);
q.setParameter("bal", 600);
q.setParameter("nm", "Ram");
em.getTransaction().begin();
int x=q.executeUpdate();
em.getTransaction().commit();
System.out.println(x+" record updated...");
1.--if we try to accees only one column then the return type will be :-
2.--if all column then the return type will be the Entity class.(internally it will
be mapped.)
3.if few columns then the return type will be Object[]. in this array each index
will represent each column
TypedQuery<String> q=em.createQuery(jpql,String.class);
q.setParameter("ano", 4);
String n= q.getSingleResult();
System.out.println(n);
TypedQuery<Integer> q=em.createQuery(jpql,Integer.class);
System.out.println(list);
for(Object[] or:list){
String name=(String)or[0];
System.out.println("Name is "+name.toUpperCase());
System.out.println("Balance is "+or[1]);
System.out.println("-------------------------");
aggregrate function:-
------------------------
min,max: Integer
avg : Double
sum : Long
ex:-
TypedQuery<Long> q=em.createQuery(jpql,Long.class);
System.out.println(result);
Named Queries:-
============
ex:-
@Entity
@NamedQuery(name = "account.getBalance",query = "from Account where balance <:bal")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int accno;
private String name;
private int balance;
JPQLMain.java:-
------------------
Query q= em.createNamedQuery("account.getBalance");
q.setParameter("bal", 5000);
NativeQueries:-
============
--here we write the Query in the term of tables and their columns
NamedNativeQuery:-
------------------------
Account.java:-
-----------------
@Entity
@NamedNativeQuery(name="allAccount" ,query = "select * from
account",resultClass=Account.class)
public class Account implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int accno;
private String name;
private int balance;
--
--
}
JPQLMain.java:-
-------------------
Query q= em.createNamedQuery("allAccount");