Maven for building Java applications By Nalin De Zoysa
Outline part 1 What is ORM? Object Relational operations – CRUD Pay attention to basic concepts Hibernate mapping mechanism DAO design pattern Integrate Hibernate with Spring Spring + Hibernate Best Practice Organization of model class Basic implementation Understanding Relationship Mapping
What is ORM?
Object Relational operations - CRUD Common O-R operations are: Create - save (persist) a new object in the database Retrieve an object from the database Update data for an object already saved in database Delete object's data from the database
Pay attention to basic concepts Persistence State of objects to live beyond the scope of the JVM so that the same state is available later. Transaction Every SQL statement, be it queries or DML, has to execute inside a database transaction. SessoinFactory A SessionFactory creates a Session object for transaction in a single threaded interaction. Session The Session acts as an agent between the application and the data store. Proxy Proxy is just a way to avoid retrieving an object until you need it
Hibernate mapping mechanism
DAO design pattern Data Access Object (DAO) is design pattern Purpose is to abstract your calls to the database. Act as an intermediary between application and DB. Easy to change database with minimal affect on code Identify bottle necks and bugs easier.
Integrate Hibernate with Spring Struts (Integrated with Spring) Spring-managed beans, Axis web services, JMS/MDBs Hibernate (Integrated with Spring)
Integrate Hibernate with Spring hibernate.dialect=${hibernate.dialect}
Spring + Hibernate HibernateDaoSupport class which is Spring-provided support class to make Hibernate integration easier. getHibernateTemplate() method returns a HibernateTemplate object which all database functionalities can be executed. Specifically, what HibernateTemplate did for you was to automatically open and close sessions and commit or rollback transactions after your code executed.
Spring + Hibernate All spring templates (hibernate, jdbc, rest, jpa etc.) have the same pros and cons: Pros: They perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want. Cons: You are coupling your application tightly to the spring framework. For this reason, Spring recommends that HibernateTemplate no longer be used. However, all of this can be achieved in an aspect-oriented way using Spring's Declarative Transaction Management.
Best Practice The javadoc of HibernateTemplate says: NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based on SessionFactory.getCurrentSession(). Reference: api/org/springframework/orm/hibernate3/HibernateTemplate.htmlhttp://static.springsource.org/spring/docs/3.1.x/javadoc- api/org/springframework/orm/hibernate3/HibernateTemplate.html
Best Practice getCurrentSession() : The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.
Organization of " land ") public class Land implements Serializable { private Long id; private Double area; private Location location; private = " id ", unique=true, nullable=false) public Long getId(){ return this.id; } public void setId(Long id) { this.id = id } //other getters and setters }
Basic landDao ") public class LandDaoHibernate implements LandDao private SessionFactory sessionFactory; public Land save(Land land){ sessionFactory.getCurrentSession.saveOrUpdate(land); return land; } public List getAllLands(){ return sessionFactory.getCurrentSession.createQuery(" from Land l ").list(); }
Understanding Relationship Mapping There are two categories of object relationships that you need to be concerned with when mapping. The first category is based on multiplicity and it includes three types: One-to-one relationships. One-to-many relationships. Also known as a many-to-one relationship Many-to-many relationships. The second category is based on directionality and it contains two types. Uni-directional relationships. A uni-directional relationship when an object knows about the object(s) it is related to but the other object(s) do not know of the original object. Bi-directional relationships. A bi-directional relationship exists when the objects on both end of the relationship know of each other
Understanding Relationship Mapping One-To-One
Understanding Relationship Mapping How we mapped in model class? public class Boy { private Long id; private String name; private “IDENTITY") public Long getId() { return this.id } //other getters " girl_id ", unique=true, nullable=true) public Girl getGirl(){ return this.girl; } } public class Girl { private Long id; private String name; private Set boies = new “IDENTITY") public Long getId() { return this.id } //other getters and mappedBy= " girl ") public Set getBoies(){ return this.boies; } }
Understanding Relationship Mapping One-To-Many / Many-To-One
Understanding Relationship Mapping How we mapped in “boy “) public class Boy { private Long id; private String name; private “IDENTITY") public Long getId() { return this.id } //other getters " girl_id ", nullable=true) public Girl getGirl(){ return this.girl; “girl “) public class Girl { private Long id; private String name; private Set boies = new “IDENTITY") public Long getId() { return this.id } //other getters and mappedBy= " girl ") public Set getBoies(){ return this.boies; } }
Understanding Relationship Mapping Many-To-Many
Understanding Relationship Mapping How we mapped in “developer “) public class Developer{ private Long id; private String name; private Set projects = new “IDENTITY") public Long getId() { return " developer_has_project ", joinColumns= " developer_id " )}, inverseJoinColumns= " project_id " )} ) public Set getProjects() { return this.projects; “project“) public class Project{ private Long id; private String name; private Set developers= new “IDENTITY") public Long getId() { return " developer_has_project ", joinColumns= " project_id" )}, inverseJoinColumns= " developer_id " )} ) public Set getDevelopers() { return this.developers; } }
Part 2 CRUD operations – Create, Retrieve, Update, Delete Query and HQL Named Query Criteria Query Example Restrictions Order Paging Lazy associations Join fetch Native SQL queries
CRUD operations – Create, Retrieve, Update, Delete Create public void createLand(Land land){ sessionFactory.getCurrentSession.saveOrUpdate(land); } public void createOwner(Owner owner){ sessionFactory.getCurrentSession.saveOrUpdate(owner); }
CRUD operations – Create, Retrieve, Update, Delete Retrieve There are several ways you can retrieve data Retrieve particular data row public Owner getOwnerById(Long ownerId){ return sessionFactory.getCurrentSession.get(Owner.class, ownerId); } public Owner getOwnerById(Long ownerId){ return sessionFactory.getCurrentSession.load(Owner.class, ownerId); }
CRUD operations – Create, Retrieve, Update, Delete Difference between get() and load() The difference is trivial: If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found.
CRUD operations – Create, Retrieve, Update, Delete Retrieve There are several ways you can retrieve data Retrieve list of record public List getAllLands(){ return sessionFactory.getCurrentSession.createQuery (" from Land l" ).list(); }
CRUD operations – Create, Retrieve, Update, Delete Update public void updateLand(Land land){ sessionFactory.getCurrentSession.saveOrUpdate(land); } public void updateOwner(Owner owner){ sessionFactory.getCurrentSession.update(owner); }
CRUD operations – Create, Retrieve, Update, Delete Delete public void deleteLand(Land land){ sessionFactory.getCurrentSession.delete(land); } public void deleteOwner(Long ownerId){ sessionFactory.getCurrentSession.update(Owner.class, ownerId); } public int deleteAllPayments(){ return sessionFactory.getCurrentSession.createQuery(" delete Payment ").executeUpdate(); }
Query and HQL Query public interface Query an object-oriented representation of a Hibernate query. A Query instance is obtained by calling getCurrentSession.createQuery(). HQL (Hibernate Query Language) HQL uses class name instead of table name, and property names instead of column name.
Query and HQL Simple query to retrieve land detail where area of land is 10,000. public List getOwnerByStatus(Double area){ return sessionFactory.getCurrentSession.createQuery(" from Land l where l.area=":area). list(); } This way is looking ugly. Is there any better solution?
Query and HQL Parameter Binding Name Parameter – set parameter public List getOwnerByStatus(Double area){ return sessionFactory.getCurrentSession.createQuery(" from Land l where l.area=:area").setParameter(" area ", area). list(); }
Query and HQL Parameter Binding Name Parameter – set data type of parameter public List getOwnerByStatus(Double area){ return sessionFactory.getCurrentSession.createQuery(" from Land l where l.area=:area").setDouble(" area ", area). list(); }
Query and HQL Parameter Binding Name Parameter – set property public List getOwnerByStatus(Land land){ return sessionFactory.getCurrentSession.createQuery(" from Land l where l.area=:area").setProperties(land). list(); }
Named Query Instead of writing HQL inside the DAO layer, you can write all necessary HQL inside the Model class and call then when necessary by name = "findPaymentByDate", query = "from Payment p where p.date = :date" = "payment", catalog = "elg_db") public class Payment implements java.io.Serializable {...
Named Query Call named query in DAO public List getPaymentByDate(Date date){ return sessionFactory.getCurrentSession().getNamedQuery(" payment. findPaymentByDate ").setParameter("date", date).list(); }
Criteria Query Hibernate Criteria API is a more object oriented and elegant alternative to Hibernate Query Language (HQL). It’s always a good solution to an application which has many optional search criteria.
Criteria Query Criteria query with Example class Find all tax payment on given particular date public List getPaymentByTypeAndDate(String type, Date date){ Payment payment = new Payment(); payment.setType(type); payment.setDate(date); Example example = Example.create(payment); return sessionFactory.getCurrentSession().createCriteria(Payment.class).add(example).list(); }
Criteria Query Criteria query with Restrictions class Find all payment amount greater than or equal to 100,000 public List getPaymentByAmount(BigDecimal amount){ return sessionFactory.getCurrentSession().createCriteria(Payment.class).add(Restrictions.ge("amount", amount)).list(); }
Criteria Query Criteria query with Order class Find all payment order by descending order public List getPaymentByDescendingOrder(){ return sessionFactory.getCurrentSession().createCriteria(Payment.class).addOrder(Order.desc("date")).list(); }
Criteria Query Criteria query pagination Find land records start from 50 th to next 20 public List getLandRecordFromStartToNext(int start, int next){ return sessionFactory.getCurrentSession().createCriteria(Payment.class).setMaxResults(next).setFirstResult(start).list(); }
Lazy associations Hibernate3 by default uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. Please be aware that access to a lazy association outside of the context of an open Hibernate session will result in an exception. Example: Owner owner = getOwnerById(ownerId); Set lands = owner.getLands(); Iterator it = lands.iterator(); //Error comes here. while(it.hasNext()){ Land land = (Land) it.next(); land.getArea(); }
Join fetch A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.
Join fetch public Owner getOwnerById(Long ownerId){ return (Owner) sessionFactory.getCurrentSession().createQuery("from Owner o join fetch o.lands join fetch o.payments where o.id=:id").setParameter("id". ownerId).list().get(0); } public Owner getOwnerById(Long ownerId){ return (Owner) sessionFactory.getCurrentSession().createCriteria(Owner.class).setFetchMode(" lands", FetchMode.JOIN).setFetchMode (" payments", FetchMode.JOIN).list().get(0); }
Native SQL queries Native SQL queries can be called as example given in below. public Payment getAllPaymentById(Long paymentId){ return (Payment) sessionFactory.getCurrentSession().createSQLQurery("select * from payment where id=:id" ).addEntity(Payment.class).setParameter("id", paymentId ).list().get(0); }