Maven for building Java applications By Nalin De Zoysa

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Spring, Hibernate and Web Services 13 th September 2014.
.NET Database Technologies: Open-Source Frameworks.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
Introduction to Structured Query Language (SQL)
Fast Track to ColdFusion 9. Getting Started with ColdFusion Understanding Dynamic Web Pages ColdFusion Benchmark Introducing the ColdFusion Language Introducing.
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
YAGDAO Yet Another DAO Hibernate Guide. yagdao   Mert Can Akkan.
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Agenda What is Hibernate Spring Integration Questions Overview
BEST PRACTICES - Java By Configuration Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Seminar on. Overview Hibernate. What is it? Hibernate. How does it work? Hibernate Tools.
Object/Relational Mapping with Hibernate Practical ORM.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Andrew S. Budarevsky Adaptive Application Data Management Overview.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
Spring Database Access Ojitha Kumanayaka Copyright © Virtusa, 2007.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Persistence – Iteration 4 Vancouver Bootcamp Aaron Zeckoski
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS. The Problem: Persistent Objects persistent object An object that can survive the process or thread that.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
Fundamentals of MyBATIS
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Sean Chambers.  ORM stands for Object Relational Mapper  Maps your POCO (plain old clr objects) to your relational model using XML config  Relieves.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Web Technologies IT230 Dr Mohamed Habib.
Hibernate (JPA) Code First Entity Relations
Entity Framework By: Casey Griffin.
Java Data Persistence Using Hibernate
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Testing a persistence layer
HAVING,INDEX,COMMIT & ROLLBACK
Chapter 8 Advanced SQL.
Developing and testing enterprise Java applications
CS4961 Software Design Laboratory Understand Aquila Backend
Chengyu Sun California State University, Los Angeles
Presentation transcript:

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); }