Download presentation
Presentation is loading. Please wait.
Published byGodfrey Boyd Modified over 9 years ago
1
Maven for building Java applications By Nalin De Zoysa http://nalin-blogging.blogspot.com/
2
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
3
What is ORM?
4
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
5
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
6
Hibernate mapping mechanism
7
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.
8
Integrate Hibernate with Spring Struts (Integrated with Spring) Spring-managed beans, Axis web services, JMS/MDBs Hibernate (Integrated with Spring)
9
Integrate Hibernate with Spring hibernate.dialect=${hibernate.dialect}
10
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.
11
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.
12
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:http://static.springsource.org/spring/docs/3.1.x/javadoc- api/org/springframework/orm/hibernate3/HibernateTemplate.htmlhttp://static.springsource.org/spring/docs/3.1.x/javadoc- api/org/springframework/orm/hibernate3/HibernateTemplate.html
13
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.
14
Organization of model class @Entity @Table(name= " land ") public class Land implements Serializable { private Long id; private Double area; private Location location; private Owner owner; @Id @GeneratedValue(stratergy = GenerationType.IDENTITY) @Column(name= " id ", unique=true, nullable=false) public Long getId(){ return this.id; } public void setId(Long id) { this.id = id } //other getters and setters }
15
Basic implementation @Repository(" landDao ") public class LandDaoHibernate implements LandDao { @Autowirted 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(); }
16
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
17
Understanding Relationship Mapping One-To-One
18
Understanding Relationship Mapping How we mapped in model class? public class Boy { private Long id; private String name; private Girl girl; @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } //other getters and setters @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name= " 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 HashSet (); @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } //other getters and setters @OneToMany(fetch=FetchType.LAZY, mappedBy= " girl ") public Set getBoies(){ return this.boies; } }
19
Understanding Relationship Mapping One-To-Many / Many-To-One
20
Understanding Relationship Mapping How we mapped in model class? @Entity @Table(name= “boy “) public class Boy { private Long id; private String name; private Girl girl; @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } //other getters and setters @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name= " girl_id ", nullable=true) public Girl getGirl(){ return this.girl; } } @Entity @Table(name= “girl “) public class Girl { private Long id; private String name; private Set boies = new HashSet (); @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } //other getters and setters @OneToMany(fetch=FetchType.LAZY, mappedBy= " girl ") public Set getBoies(){ return this.boies; } }
21
Understanding Relationship Mapping Many-To-Many
22
Understanding Relationship Mapping How we mapped in model class? @Entity @Table(name= “developer “) public class Developer{ private Long id; private String name; private Set projects = new HashSet (); @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name= " developer_has_project ", joinColumns= {@JoinColumn(name= " developer_id " )}, inverseJoinColumns= {@JoinColumn(name= " project_id " )} ) public Set getProjects() { return this.projects; } } @Entity @Table(name= “project“) public class Project{ private Long id; private String name; private Set developers= new HashSet (); @Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id } @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name= " developer_has_project ", joinColumns= {@JoinColumn(name= " project_id" )}, inverseJoinColumns= {@JoinColumn(name= " developer_id " )} ) public Set getDevelopers() { return this.developers; } }
23
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
25
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); }
26
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); }
27
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.
28
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(); }
29
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); }
30
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(); }
31
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.
32
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?
33
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(); }
34
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(); }
35
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(); }
36
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 Named Query. @NamedQueries({ @NamedQuery( name = "findPaymentByDate", query = "from Payment p where p.date = :date" ) }) @Entity @Table(name = "payment", catalog = "elg_db") public class Payment implements java.io.Serializable {...
37
Named Query Call named query in DAO public List getPaymentByDate(Date date){ return sessionFactory.getCurrentSession().getNamedQuery(" payment. findPaymentByDate ").setParameter("date", date).list(); }
38
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.
39
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(); }
40
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(); }
41
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(); }
42
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(); }
43
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(); }
44
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.
45
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); }
46
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); }
47
www.hSenidbiz.com www.hSenidbiz.com
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.