Professional Documents
Culture Documents
//close session
newSession.close();
-load():
-It will always return a �proxy� without hitting the database.
-return proxy object first and load data only when it required
-load is better because it support lazy loading.
-If no row found , it will throws an ObjectNotFoundException.
-throw exception when data is not found.we should used when data is exist.
Ehcache is a popular open source Java cache that can be used as a Hibernate second
level cache.
-EHCache is best choice to used second level cache.
1) Add hibernate-EHCache dependency in pom .xml or used jar file.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.5.Final</version>
</dependency>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
4) Annotate entity beans with @Cache annotation and caching strategy to use. For
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "ADDRESS")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {
5) Different caching-strategy :
-none : No caching will perform.
-read-only : if u performing read,but not modify instance of persistance class
then used read-only cache.
-read-write : If the application needs to update data, a read-write cache might be
appropriate.
Persistent :
-When object is associated with a unique session it is in persistance state.
-Any instace return by a get() and load() method is persistent.
Detached :
-When an object is persistent but not associated with any session,its in detached
state.
-Detached object can be made persistent by calling update(), saveOrUpdate(),lock()
or replicate()
persist():
-persist is similar to save ,with transaction and add entity to persistance state.
-better to used because we need to perform database operation in transacion only.
-also persist doesn't return save entity id immediately.
-if we have mapping objects then save both objects at same time.
saveOrUpdate();
-results into save or update query based on input provided.
-If data persist in database update query is called.
-We can use saveOrUpdate() without transaction also but again we will face mapped
object not getting save untill we will flushed session.
merge():
-hibernate merge can be used to update existing values.
-method create copy of entity object we passed and return it.
-the return object is part of persistance context and tracked for any changes,
passed object is not tracked.
Ordered collection :
-If we are using hibernate framework to load collection data from database ,we can
used it's Criteria API to use "order by" clause.
-Order list is better then sorted list because the actual sorting is done at
database level which is faster and never cause memmory issues.
-CriteriaAPI provide Projection that we can used for aggregate functions such as
sum(),min(),max() etc.
-CriteriaAPI can be used for fetching results with conditions,usefull methods is
add() where we can add Restriction.
-CriteriaAPI can be used with Projection List to fetch selected column only.
-CriteriaAPI can be used for join queries by joining multiple tables.
-CriteriaAPI provides addOrder() methods that we can use for ordering results.
import java.util.Arrays;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
// Get with ID, creating new Criteria to remove all the settings
criteria = session.createCriteria(Employee.class)
.add(Restrictions.eq("id", new Long(3)));
Employee emp = (Employee) criteria.uniqueResult();
System.out.println("Name=" + emp.getName() + ", City="
+ emp.getAddress().getCity());
//Pagination Example
empList = session.createCriteria(Employee.class)
.addOrder(Order.desc("id"))
.setFirstResult(0)
.setMaxResults(2)
.list();
for(Employee emp4 : empList){
System.out.println("Paginated Employees::"+emp4.getId()
+","+emp4.getAddress().getCity());
}
//Like example
empList = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "%i%"))
.list();
for(Employee emp4 : empList){
System.out.println("Employees having 'i' in
name::"+emp4.getName()+","+emp4.getAddress().getCity());
}
//Projections example
long count = (Long) session.createCriteria(Employee.class)
.setProjection(Projections.rowCount())
.add(Restrictions.like("name", "%i%"))
.uniqueResult();
System.out.println("Number of employees with 'i' in name="+count);
Q What is your choice while writing queries within Hibernate - criteria or HQL ?
- I prefer using Criteria for Dynamic queries and HQL for static queries.
NOTE :- https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-
cascadetype-persist-example/#:~:text=Cascading%20is%20a%20phenomenon
%20involving,CascadeType.
Q HibernateValidation ?
-Data validation must be done before it persist.
-Validation is cross cutting concern so we should try to keep it apart from
business logic.
-Need to add dependency : hibernate-validator and hibernate-validation.
-Annotaion use for validation :
@NotNull
@unique
@Email
@Min
@Max
@Size
@CreditCardNumber
@Valid
Q Should all the mapping files of hibernate have .hbm.xml extension to work
properly?
No not mandatory to keep .hbm.xml only.
session.saveOrUpdate()
-Insert if its unique key means new record.
-update if record already exist.
Q What are the benefits of hibernate over JDBC?
hibernate :
-database independent.
-no need to write connection pool code, manage by hibernate internally
JDBC:
-database specific query.
-need to write connection code.
https://www.callicoder.com/hibernate-spring-boot-jpa-composite-primary-key-example/
https://www.journaldev.com/3633/hibernate-interview-questions-and-
answers#hibernate-overview