47
Maven for building Java applications By Nalin De Zoysa http://nalin-blogging.blogspot.com/

Maven for building Java applications By Nalin De Zoysa

Embed Size (px)

Citation preview

Page 1: Maven for building Java applications By Nalin De Zoysa

Maven for building Java applicationsBy Nalin De Zoysa

http://nalin-blogging.blogspot.com/

Page 2: 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

Page 3: Maven for building Java applications By Nalin De Zoysa

What is ORM?

Page 4: Maven for building Java applications By Nalin De Zoysa

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

Page 5: Maven for building Java applications By Nalin De Zoysa

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

Page 6: Maven for building Java applications By Nalin De Zoysa

Hibernate mapping mechanism

Page 7: Maven for building Java applications By Nalin De Zoysa

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.

Page 8: Maven for building Java applications By Nalin De Zoysa

Integrate Hibernate with Spring

Struts(Integrated with Spring)

Spring-managed beans, Axis web services,JMS/MDBs

Hibernate (Integrated with Spring)

Page 9: Maven for building Java applications By Nalin De Zoysa

Integrate Hibernate with Spring<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-

method="close">

<property … />

</bean>

<bean id="sessionFactory“ class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

<property name="dataSource" ref="dataSource"/>

<property name="packagesToScan" value=“orm.mapping"/>

<property name="hibernateProperties">

<value>

hibernate.dialect=${hibernate.dialect}

</value>

</property>

</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"/>

</bean>

Page 10: Maven for building Java applications By Nalin De Zoysa

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.

Page 11: Maven for building Java applications By Nalin De Zoysa

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.

Page 12: Maven for building Java applications By Nalin De Zoysa

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.html

Page 13: Maven for building Java applications By Nalin De Zoysa

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.

Page 14: Maven for building Java applications By Nalin De Zoysa

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

}

Page 15: Maven for building Java applications By Nalin De Zoysa

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<Land> getAllLands(){

return sessionFactory.getCurrentSession.createQuery(" from Land l ").list();

}

}

Page 16: Maven for building Java applications By Nalin De Zoysa

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

Page 17: Maven for building Java applications By Nalin De Zoysa

Understanding Relationship Mapping One-To-One

Page 18: Maven for building Java applications By Nalin De Zoysa

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<Boy> boies = new HashSet<Boy>();

@Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id }

//other getters and setters

@OneToMany(fetch=FetchType.LAZY, mappedBy= " girl ") public Set<Boy> getBoies(){ return this.boies; } }

Page 19: Maven for building Java applications By Nalin De Zoysa

Understanding Relationship Mapping One-To-Many / Many-To-One

Page 20: Maven for building Java applications By Nalin De Zoysa

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<Boy> boies = new HashSet<Boy>();

@Id @GeneratedValue(GenerationType= “IDENTITY") public Long getId() { return this.id }

//other getters and setters

@OneToMany(fetch=FetchType.LAZY, mappedBy= " girl ") public Set<Boy> getBoies(){ return this.boies; } }

Page 21: Maven for building Java applications By Nalin De Zoysa

Understanding Relationship Mapping Many-To-Many

Page 22: Maven for building Java applications By Nalin De Zoysa

Understanding Relationship Mapping How we mapped in model class?

@Entity @Table(name= “developer “)public class Developer{

private Long id; private String name; private Set<Project> projects = new HashSet<Project>(); @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<Project> getProjects()

{ return this.projects; }}

@Entity @Table(name= “project“)public class Project{

private Long id; private String name; private Set<Developer> developers= new HashSet<Developer>(); @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<Developer> getDevelopers()

{ return this.developers; }}

Page 23: Maven for building Java applications By Nalin De Zoysa

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

Page 24: Maven for building Java applications By Nalin De Zoysa
Page 25: Maven for building Java applications By Nalin De Zoysa

CRUD operations – Create, Retrieve, Update, Delete Createpublic void createLand(Land land){

sessionFactory.getCurrentSession.saveOrUpdate(land);

}

public void createOwner(Owner owner){

sessionFactory.getCurrentSession.saveOrUpdate(owner);

}

Page 26: Maven for building Java applications By Nalin De Zoysa

CRUD operations – Create, Retrieve, Update, Delete Retrieve

There are several ways you can retrieve data

Retrieve particular data rowpublic Owner getOwnerById(Long ownerId){

return sessionFactory.getCurrentSession.get(Owner.class, ownerId);

}

public Owner getOwnerById(Long ownerId){

return sessionFactory.getCurrentSession.load(Owner.class, ownerId);

}

Page 27: Maven for building Java applications By Nalin De Zoysa

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.

Page 28: Maven for building Java applications By Nalin De Zoysa

CRUD operations – Create, Retrieve, Update, Delete Retrieve

There are several ways you can retrieve data

Retrieve list of recordpublic List<Land> getAllLands(){

return sessionFactory.getCurrentSession.createQuery

(" from Land l" ).list();

}

Page 29: Maven for building Java applications By Nalin De Zoysa

CRUD operations – Create, Retrieve, Update, Delete Updatepublic void updateLand(Land land){

sessionFactory.getCurrentSession.saveOrUpdate(land);

}

public void updateOwner(Owner owner){

sessionFactory.getCurrentSession.update(owner);

}

Page 30: Maven for building Java applications By Nalin De Zoysa

CRUD operations – Create, Retrieve, Update, Delete Deletepublic 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();

}

Page 31: Maven for building Java applications By Nalin De Zoysa

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.

Page 32: Maven for building Java applications By Nalin De Zoysa

Query and HQL Simple query to retrieve land detail where

area of land is 10,000.

public List<Land> 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?

Page 33: Maven for building Java applications By Nalin De Zoysa

Query and HQL Parameter Binding

Name Parameter – set parameter

public List<Land> getOwnerByStatus(Double area){

return sessionFactory.getCurrentSession

.createQuery(" from Land l where l.area=:area")

.setParameter(" area " , area)

. list();

}

Page 34: Maven for building Java applications By Nalin De Zoysa

Query and HQL Parameter Binding

Name Parameter – set data type of parameter

public List<Land> getOwnerByStatus(Double area){

return sessionFactory.getCurrentSession

.createQuery(" from Land l where l.area=:area")

.setDouble(" area " , area)

. list();

}

Page 35: Maven for building Java applications By Nalin De Zoysa

Query and HQL Parameter Binding

Name Parameter – set property

public List<Land> getOwnerByStatus(Land land){

return sessionFactory.getCurrentSession

.createQuery(" from Land l where l.area=:area")

.setProperties(land)

. list();

}

Page 36: Maven for building Java applications By Nalin De Zoysa

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 {

...

Page 37: Maven for building Java applications By Nalin De Zoysa

Named Query Call named query in DAOpublic List<Payment> getPaymentByDate(Date date){

return sessionFactory.getCurrentSession()

.getNamedQuery(" payment. findPaymentByDate ")

.setParameter("date", date).list();

}

Page 38: Maven for building Java applications By Nalin De Zoysa

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.

Page 39: Maven for building Java applications By Nalin De Zoysa

Criteria Query Criteria query with Example class Find all tax payment on given particular date

public List<Payment> 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();

}

Page 40: Maven for building Java applications By Nalin De Zoysa

Criteria Query Criteria query with Restrictions class Find all payment amount greater than or

equal to 100,000

public List<Payment> getPaymentByAmount(BigDecimal amount){

return sessionFactory.getCurrentSession().createCriteria(Payment.class)

.add(Restrictions.ge("amount", amount)).list();

}

Page 41: Maven for building Java applications By Nalin De Zoysa

Criteria Query Criteria query with Order class Find all payment order by descending order

public List<Payment> getPaymentByDescendingOrder(){

return sessionFactory.getCurrentSession().createCriteria(Payment.class)

.addOrder(Order.desc("date")).list();

}

Page 42: Maven for building Java applications By Nalin De Zoysa

Criteria Query Criteria query pagination Find land records start from 50th to next 20

public List<Land> getLandRecordFromStartToNext(int start, int next){

return sessionFactory.getCurrentSession().createCriteria(Payment.class)

.setMaxResults(next).setFirstResult(start).list();

}

Page 43: Maven for building Java applications By Nalin De Zoysa

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<Land> lands = owner.getLands();

Iterator<Land> it = lands.iterator(); //Error comes here.

while(it.hasNext()){

Land land = (Land) it.next();

land.getArea();

}

Page 44: Maven for building Java applications By Nalin De Zoysa

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.

Page 45: Maven for building Java applications By Nalin De Zoysa

Join fetchpublic 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);

}

Page 46: Maven for building Java applications By Nalin De Zoysa

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

}

Page 47: Maven for building Java applications By Nalin De Zoysa

www.hSenidbiz.comwww.hSenidbiz.com