hibernate session api
hibernate session api
0. org.hibernate.SessionFactory API
getCurrentSession vs openSession
OR
public Session getCurrentSession() throws HibernateException
Opens new session , if one doesn't exist , otherwise continues with the exisitng
one.
Gets automatically closed upon Tx boundary(commit/rollback) or thread over(since
current session is bound to current thread --mentioned in hibernate.cfg.xml
property ---current_session_context_class=thread)
save() method auto persists transient POJO on the DB(upon committing tx) & returns
unique serializable ID generated by hibernate frmwork(if @GeneratedValue is used
for id.)
using HQL -- Hibernate Query Language --- Objectified version of SQL --- where
table names will be replaced by POJO class names & table col names will replaced by
POJO property names.
(JPA--- Java Persistence API compliant syntax --- JPQL )
eg --- SQL -- select * from books
HQL --- "from BookPOJO"
eg JPQL -- "select b from BookPOJO b"
eg : Query<Book> q=hs.createQuery(hql/jpql,Book.class);
List<T> getResultList()
Execute a SELECT query and return the query results as a generic List<T>.
T -- type of POJO / Result
eg : hs,tx
String jpql="select b from Book b";
try {
List<Book> l1=hs.createQuery(jpql,Book.class).getResultList();
}
Usage ---
String hql="select b from BookPOJO b";
List<BookPOJO> l1=hibSession.createQuery(hql).getResultList();
String hql="select b from BookPOJO b where b.price < :sp_price and b.author
= :sp_auth";
List<Book> l1 =
hibSession.createQuery(hql,Book.class).setParameter("sp_price",user_price).setParam
eter("sp_auth",user_auth).getResultList();
4. Updating POJOs --- Can be done either with select followed by update or ONLY
with update queries(following is eg of 2nd option
commonly known as bulk update)
Objective : Reduce price of all books with author=specified author , published
before a sepecific date
String jpql = "update BookPOJO b set b.price = b.price - :disc where b.author = :au
and b.publishDate < :dt ";
set named In params
exec it (executeUpdate) ---
int updateCount= hs.createQuery(jpql).setParameter("disc", disc).setParameter("dt",
d1).executeUpdate();
---POJO is marked for removal , corresponding row from DB will be deleted after
comitting tx & will be removed form entity cache(l1 cache) closing of session.
OR
5.5
One can use directly "delete HQL" & perform deletions.
eg
int deletedRows = hibSession.createQuery ("delete Subscription s where
s.subscriptionDate < :today").setParameter ("today", new Date ()).executeUpdate ();
---------------
Detailed API
0. SessionFactory API
getCurrentSession vs openSession
2.
public Serializable save(Object ref)
save --- if u give some non-null id(existing or non-existing) while calling
save(ref) --doesn't give any exc.
Ignores ur passed id & creates its own id & inserts a row.
3. saveOrUpdate
public void saveOrUpdate(Object ref)
--either inserts/updates or throws exc.
null id -- fires insert (works as save)
non-null BUT existing id -- fires update (works as update)
non-null BUT non existing id -- throws StaleStateException --to indicate that we
are trying to delete or update a row that does not exist.
3.5
merge
public Object merge(Object ref)
I/P -- either transient or detached POJO ref.
O/P --Rets PERSISTENT POJO ref.
4. get vs load
& LazyInitilalizationException.
5. update
Session API
public void update(Object object)
Update the persistent instance with the identifier of the given detached instance.
I/P --detached POJO containing updated state.
Same POJO becomes persistent.
Exception associated :
1. org.hibernate.TransientObjectException: The given object has a null identifier:
i.e while calling update if u give null id. (transient ----X ---persistent via
update)
8.
public void clear()
It will detach all the entities associated with the session object(L1 cache) i.e
all persistent entities become detached.
But Databse Connection is not returned to connection pool n L1 cache is NOT
destroyed.
(Completely clears the session. Evicts all loaded instances and cancel all pending
saves, updates and deletions)
9. void close()
When the object is in persistent state , whatever changes we made to the object
state will be reflected in the databse only at the end of transaction.
12.
void refresh(Object ref) -- ref --persistent or detached
This method is used to get the latest data from database and make
corresponding modifications to the persistent object state.
(Re-reads the state of the given instance from the underlying database
API of org.hibernate.query.Query<T>
Return the query results as an Iterator. If the query contains multiple results per
row, the results are returned Object[].
Set the maximum number of rows to retrieve. If not set, there is no limit to
the number of rows retrieved.
Set the first row to retrieve. If not set, rows will be retrieved beginnning
from row 0. (NOTE row num starts from 0)
5. org.hibernate.query.Query API
<T> T getSingleResult()
Throws:
NoResultException - if there is no result
NonUniqueResultException - if more than one result
IllegalStateException - if called for a JPQL UPDATE or DELETE statement
Usgae
Department d1 = (Department)
session.getNamedQuery(DepartmentEntity.GET_DEPARTMENT_BY_ID).setInteger("id", 1);
2.
public Serializable save(Object ref)
save --- if u give some non-null id(existing or non-existing) while calling
save(ref) --doesn't give any exception
Ignores your passed id & creates its own id & inserts a row.
3. saveOrUpdate
public void saveOrUpdate(Object ref)
--either inserts/updates or throws exc.
null id -- fires insert (works as save)
non-null BUT existing id -- fires update (works as update)
non-null BUT non existing id -- throws StaleStateException --to indicate that we
are trying to delete or update a row that does not exist.
3.5
merge
public Object merge(Object ref)
I/P -- either transient or detached POJO ref.
O/P --Rets PERSISTENT POJO ref.
4. get vs load
& LazyInitilalizationException.
5. update
Session API
public void update(Object object)
Update the persistent instance with the identifier of the given detached instance.
I/P --detached POJO containing updated state.
Same POJO becomes persistent.
Exception associated :
1. org.hibernate.TransientObjectException: The given object has a null identifier:
i.e while calling update if u give null id. (transient ----X ---persistent via
update)
8.
void clear()
When clear() is called on session object all the objects associated with the
session object(L1 cache) become detached.
But Databse Connection is not returned to connection pool.
(Completely clears the session. Evicts all loaded instances and cancel all pending
saves, updates and deletions)
9. void close()
When the object is in persistent state , whatever changes we made to the object
state will be reflected in the databse only at the end of transaction.
12.
void refresh(Object ref) -- ref --persistent or detached
This method is used to get the latest data from database and make
corresponding modifications to the persistent object state.
(Re-reads the state of the given instance from the underlying database