developing enterprise applications spring, hibernate & ext-js kesav kolla
TRANSCRIPT
DEVELOPING ENTERPRISE APPLICATIONSSPRING, HIBERNATE & EXT-JS
Kesav Kolla
Agenda
Enterprise Readiness New & Noteworthy
Agenda
ORM Understanding Hibernate Entity design with JPA annotations Query Language Object caching
Spring Architecture of spring Building Data access layer using spring Spring MVC
Web 2.0 Developing rich user interfaces using Ext-JS AJAX Access data using REST+JSON
About Me
15 years of IT experience Worked in reputed organizations (TCS,
CitiCorp, Kaiser Permanente, IBM) Certified developer (Java, .NET, Share
Point, Biztalk Server, Cache many others) Contributed to open source projects
(Jdom, dom4j, Orion application server) Active member in communities
(Ensemble, Cache) Expertise in Security, Message
Integration, SOA, Web applications Conducted several training camps
Introduction
General Q&A about Java Your knowledge with J2EE Understanding of Annotations
& XML Open source experience Web development experience What’s your expectations
Enterprise Readiness
SCM Build Management Unit Testing Project Management Coding guidelines Working in teams Patterns & Practices Issue tracking Documentation
New & Noteworthy
Virtualization Cloud computing
Amazon Microsoft Azure Google
Mobile computing iOS4 Android Windows Mobile
New & Noteworthy
Java J2EE 1.6 (EJB 3.1, Servlets 3.0) Dynamic Languages (Groovy, Scala)
Microsoft Technologies .NET 4.0 (ASP.NET MVC, COM Interop, WCF,
Entity Framework) WCF Data services Silverlight 4 Visual Studio 2010 Web matrix (IIS Express, Razor view engine)
New & Noteworthy
Google Google App Engine Google AJAX libraries Google Maps, Google Docs Google Charts & Data visualization GWT
New & Noteworthy
High Scalability NoSQL Databases Hadoop
Dynamic & Functional languages Python Erlang JavaScript
HTML5 OData
What is ORM?
Object-oriented programming technologies are typically used to implement business logic.
Relational databases are used for persistent data storage.
Impedance mismatch between the two paradigms: objects vs relations Estimated that 30-40% of a JDBC application involves
correcting data from tuples to object instances and back again
ORM toolkits are designed to address this impedance. More than 60 different ORM toolkits are available in
various different programming languages. Almost all programming language has some type of ORM.
ORM
To exploit object behavior fully, data-access from within an object-oriented programming should offer: Uniqueness Inheritance Change detection Database independence Lazy loading
ORM
Mappings are usually a correspondence between a row in a normalized table and a class instance Specified using metadata For example, a row of the Employee table will correspond to an
instance of the Employee object within the application Mappings are often not isomorphic Sophisticated ORMs such as Hibernate and LINQ permit object models
that differ substantially from the underlying relational store Need to establish a correspondence between an in-memory object
and a database row Must be independent of how the object was acquired: a database
query, or navigating a reference to another object Predicated on the existence of primary keys in the database
Many ORM toolkits attempt to offer database independence, so that applications can be ported from one DBMS to another Create common APIs and models to interact with a variety of DBMS
platforms
Why ORMs useful?
Eliminates tedious, repetitive code that instantiates object instances from tuples using a SELECT statement and a CURSOR
Insulates, to some extent, the application developer from vendor-specific SQL extensions
Permits the application developer to exploit object-orientation and model and manipulate the application view differently from the relational model
Data manipulation can be done at the object level, rather than (only) at a SQL statement level
EJB
EJB Provides Basic Persistence (CMP) Method-level transaction management Automatic management of associations EJBQL provides a very basic object query
language Problems with EJB
Complex deployment descriptors No polymorphism Can’t test outside container EJBQL is too limited (No dynamic queries, no
aggregation/projection, no outer-join fetching)
Hibernate
Open-source, LGPL Java ORM toolkit Originally developed by Christian Bauer,
Gavin King, and a worldwide team of developers
Now maintained by a team at JBoss (Redhat) led by Steve Ebersole
Ported to the .NET environment (C#), called Nhibernate
http://hibernate.org
Hibernate
Presentation/Business
Java Application (Swing, JSP,
Beans etc…)
Persistance Interaction Persistance
RDBMS
Custom Direct JDBC access code
Hibernate
Hibernate
POJOJPA
POJOJPA
Lab1
First POJO Creating Hibernate mappings Test Basic CRUD operations
XML vs Annotations
For Annotations Co-located (inline) with the class Simplified declaration reduce errors Faster to develop and test = reduced costs
For XML Separates OO model and persistence Integration control outside of the class
definition (follows previous argument) Separation of concerns between
development and deployment (e.g., changing database providers)
JPA
JPA is a coordinating layer (proxy) between persistence providers and integrating components
JPA provides Object attribute to database table mapping (similar
to ORMs – e.g., Hibernate) Query language (JPQL) abstraction Transaction support Interceptors (proxy methods for before/after
operations) Meta configuration
XML configuration Annotation (@)
JPA
JPA Provides Higher-level (simplified) abstraction of CRUD
(still allowing access to underlining frameworks (ORMs) and database (JDBC)
Lifecycle management Standards-based approach
Object
JPA JDBCObject ORM
RDBMS
Mapping data with JPA annotations Data is mapped by either (cannot mix within a class)
By field Annotations at each (at least one) field Scoping: package, protected, private - public not allowed
public class Data {
@Id
long uniqueId;
}
By property Requires JavaBean conventions - setter/getter methods
public class Data {
@Id
public long getUniqueId() { return uniqueId; }
}
Common JPA Annotations
Annotation Description
@Entity Declares a Java Object to be persistent
@Table Maps a Java Object to a database table (support for legacy integration)
@Column Maps a Java attribute to a table column (support for legacy integration)
@Transient Declares attribute to be not persistent
@Id Primary key(s)
@NamedQuery Defines prepared queries
Other annotations include: @Embeddable, @Basic, @Temporal, @Inheritance, @Lob, @PersistenceContext, @PersistenceUnit, @Resource, @QueryHint, …
Primary Keys
@Id Key classes must
Define equal() and hashCode() Empty constructor Public class
Compound PKs Multiple @Id references PK class (@IdClass, @EmbeddedId)
Generators @TableGenerator
Considered most portable of the automatic ID generators Typically a table with two columns is used (sequence name, sequence count)
@SequenceGenerator Database provided sequence generator (not all databases provide sequence objects, i.e., Oracle’s SEQUENCE
and INCREMENT) Typically a table with two columns is used (sequence name, sequence count)
@GeneratedValue Custom ID generator (you provide the method)
Lab2
Writing JPA Entities Setup the persistence context Basic CRUD operations using JPA
Validation
Validation Annotations @AssertTrue/AssertFalse(Boolean value) - Boolean @DecimalMax/DecimalMin(String value) – BigDecimal, BigInteger, String, byte/Byte, short/Short, int/Integer,
long/Long @Digits(int integer, int fraction) - BigDecimal,
BigInteger, String, byte/Byte, short/Short, int/Integer, long/Long @Future/Past() – Date, Calendar @Max/Min(long value) – BigDecimal, BigInteger, String, byte/Byte, short/Short, int/Integer, long/Long @Null/NotNull() – Object @Pattern(String regexp, Flag flags) - String @Size(int min, int max) – String, Collection, Map,
Array.length
JP-QL
Hibernate allows several ways to query for objects JP-QL – JPA Query Language Criteria Queries Query by Examples Native SQL Queries
Full Support for relational operations Inner/Outer/Full Joins Projection Aggregation (max, avg…) grouping Ordering Sub Queries SQL function calls
JP-QL
Some query examples showing how to query, project and aggregate Simple HQL query HQL with filters and named parameters Projection Aggregation Criteria Queries
JP-QL
Simplest JP-QL Query Return all events
//queryList<Event> events =
(List<Event>)em.createQuery(“from Event”, Event.class).getResultList();
Lab3
All about queries
Spring Framework
Spring is a lightweight inversion of control and aspect oriented container framework
Spring makes developing J2EE application easier and more fun!!!
Introduced by Rod Johnson in “J2EE Design & Development”
Spring
Spring is a non-invasive application development framework that aims to make the life easier for Java/J2EE developers, by Providing a DI (or IoC) container. Providing an AOP framework that delivers
services such as declarative transaction management.
Providing abstraction for more complicated (J2EE) services and APIs, which removes lot of ”boilerplate code”.
DI + AOP + Service Abstraction = Power to the POJO
Spring IoC
IoC Externalizes the creation and management of
component dependencies IoC has two subtypes and four flavors
Dependency Lookup Dependency pull Contextualized dependency lookup
Dependency Injection Constructor dependency injection Setter dependency injection
IoC usually works in the context of a container
Benefits of IoC
Reduce glue code Externalize dependencies Manage dependencies in a single place Improve testability Foster good application design
IoC
Traditional Class Foo needs a reference to an
instance of a class that implements IBar public function doSomething()
{IBar bar = new Bar();
} Very tight coupling
IoC
Dependency Pull Centralized registry public function doSomething()
{IRegstry registry = getRegistry();IBar bar = registry.lookup(“bar”);
} Requires common way to get access to
registry (Singleton, Extension)
IoC
Constructor Dependency Injection Dependencies passed into component’s
constructor public function Foo(IBar bar)
{this.bar = bar;
}public function doSomething(){
// instance level access to bar}
Requires container to create instance
IoC
Setter Dependency Injection Dependencies set on component through
setter methods public function set bar(bar:IBar)
{this.bar = bar;
}public function doSomething(){// instance level access to bar}
Need to know what to set
IoC
Lookup requires repeated code, interface implementation, and/or subclassing
Lookup in general is more complex Injection lets you easily manually create
instances Injection is passive Setter Injection better when a component
can provide defaults Setter Injection allows changes to
dependencies of an existing component
Spring Framework
Spring is a glue framework that is gives an easy way of configuring and resolving dependencies throughout the J2EE stack. It has MVC, AOP, declarative management of beans and services, JDBC, JMS, and other useful abstractions.
Spring ties many other technologies together in a consistent approach.
Spring also provides declarative access to enterprise services via AOP (Aspect Oriented Programming). J2EE services exposed through aspects ,usually hidden behind an EJB container, helps to facilitate testing and consequently ease of development.
The added ease of development and maintenance make the value proposition presented with Spring very attractive to most companies.
Spring Modules
Spring Framework
Core Container The Core Container consists of the Core, Beans,
Context, and Expression Language modules. The Core and Beans modules provide the
fundamental parts of the framework, including the IoC and Dependency Injection features
The Context module inherits its features from the Beans module and adds support for event-propagation, resource-loading, and the transparent creation of contexts
The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.
Spring Framework
Data Access/Integration The Data Access/Integration layer consists of the
JDBC, ORM, OXM, JMS and Transaction modules. The JDBC module provides a JDBC-abstraction
layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.
The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
Spring Framework
Web The Web-Servlet module contains Spring's model-
view-controller (MVC) implementation for web applications.
Provides an easy REST services AOP and Instrumentation
Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated
Test The Test module supports the testing of Spring
components with JUnit or TestNG.
Spring Framework
Spring IoC
A Spring IoC container manages one or more beans. Within the container itself, these bean definitions are
represented as BeanDefinition objects, which contain (among other information) the following metadata: A package-qualified class name: typically the actual
implementation class of the bean being defined. Bean behavioral configuration elements, which state how
the bean should behave in the container (scope, lifecycle callbacks, and so forth).
References to other beans that are needed for the bean to do its work; these references are also called collaborators or dependencies.
Other configuration settings to set in the newly created object, for example, the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.
Spring IoC
The bean definition class name scope constructor arguments properties autowiring mode dependency checking mode lazy-initialization mode initialization method destruction method
Spring IoC
Features of Managed Beans: Default to Singleton’s Properties can be set via dependency injection
Referencestoothermanagedbeans Strings Primitivetypes Collections(lists,set,map,props) “InnerBeans”
“Auto wiring” Parameters may be externalized to property
files
Spring IoC
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } }
Spring IoC
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested <ref/> element --> <property name="beanOne"><ref
bean="anotherExampleBean"/></property>
<!-- setter injection using the neater 'ref' attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/></bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Spring IoC
public class ExampleBean {
private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean( AnotherBean anotherBean, YetAnotherBean
yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; }}
Spring IoC
<bean id="exampleBean" class="examples.ExampleBean">
<!-- constructor injection using the nested <ref/> element --> <constructor-arg> <ref bean="anotherExampleBean"/> </constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref="yetAnotherBean"/> <constructor-arg type="int" value="1"/></bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Spring Lab1
Spring Beans Dependency Injection/IoC Context Lifecycle
OO Design is good but…
The oop languages makes the code design more reusable and compact.
But sometimes it makes the code scattered in number of modules.
More code plumbing has to be done… Example : adding message logging in each
of class methods makes the logging code scattered in number of methods and classes.
This makes code maintenance and updation a tedious work.
AOP is the solution…
Aspect Oriented Programming(AOP)’ addresses these issues.
Instead of adding the logging code in each of the methods, you delegate the logging functionality ( concern ) across number of methods to an aop container and specify which methods require logging applied.
The container will call the logging aspect of the code when the methods are invoked on the proxy object returned by the Container.
AOP Terminology
JoinPoint A point during the execution of a program, such as the
execution of method or exception handling. We can insert additional logic at JoinPoint In Spring AOP JoinPoint always represents a method
execution. Advice
Action taken at a particular JoinPoint PointCut
A declarative condition that identifies for which JoinPoint the advice should fire
Aspect An aspect is a modularization of a crosscutting concern.
The gathering together of code that might otherwise have been scattered. It is termed as the combination of PointCut and Advice.
Types of AOP
Static AOP Aspects are typically introduced in byte code
during the build process or via custom class loader at runtime
AspectJ (byte code manipulation at compile time)
JBoss AspectWerkz (Class loader approach) Dynamic AOP
Create “proxies” for all advised objects Slightly poorer performance Easier to configure Spring
Spring AOP Support
AOP Framework that builds on the aopalliance interfaces.
Aspects are coded with pure Java code. Spring aspects can be configured using its
own IoC container. Objects obtained from the IoC container can be
transparently advised based on configuration Spring AOP has built in aspects such as
providing transaction management, performance monitoring and more for your beans.
Spring supports proxy based AOP to bean methods.
Spring Advices
Spring AOP supports the following advices: Before advice : (Advice is applied before method is
executed) After returning advice : (Advice is applied after
method is returned normally without throwing any Exceptions)
After throwing advice : Advice to be executed if a method exits by throwing an exception.
Around advice : Advice that surrounds a join point such as a method invocation. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
Spring AOP Features
Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a J2EE web container or application server or in a desktop application.
Spring AOP currently supports only method execution join points.
The aspects can be programmatically or declaratively configured through xml.
The aspects can be configured with jdk1.5 annotations features.
Spring AOP
Writing Aspect Enable @AspectJ Support
<aop:aspectj-autoproxy/> Any bean defined in the application context with a
class that has @AspectJ annotation is an aspect. Declaring PointCut
PointCut declaration has two parts A signature comprising a name and any parameters A PointCut expression that determines exactly which
method executions we are interested in.@Pointcut("execution(* transfer(..))")// the pointcut
expressionprivate void anyOldTransfer() {}// the pointcut
signature
Spring PointCut Designators (PCD)
Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions:
execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
@target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type
@args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)
@within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)
@annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation
Examples
Spring AOP users are likely to use the execution pointcut designator the most often. The format of an execution expression is: execution(modifiers-pattern? ret-type-pattern declaring-type-
pattern? name-pattern(param-pattern) throws-pattern?) the execution of any public method:
execution(public * *(..)) the execution of any method with a name beginning with
"set": execution(* set*(..))
the execution of any method defined by the AccountService interface: execution(* com.xyz.service.AccountService.*(..))
the execution of any method defined in the service package: execution(* com.xyz.service.*.*(..))
Spring AOP Lab
Spring AOP Lab Configuration Writing Aspects Writing Pointcuts
Spring DAO
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way.
This allows one to switch between the aforementioned persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.
Annotations used for configuring DAO or Repository classes @Repository @PersistenceContext
Integration Styles Spring’s DAO template Coding DAOs against plain JPA/Hibernate etc…
Spring DAO
JpaTemplate and JpaDaoSupport DAOs receive EntityManagerFactory through
dependency injection Config (from applicationContext.xml):
<beans> <bean id="eventDAO"
class="com.contoso.evtmgmt.EventDAO"> <property name="entityManagerFactory" </bean> </beans>
Code…
Spring DAO
DAO code fragment:public class EventDAOJpaImpl extends
JpaDaoSupport implements IEventDAO {public List<Event> getAllEvents() {
List<Event> results = getJpaTemplate().findByNamedQuery("event.all");return results;
}
}
Spring DAO
DAOs based on plain JPA Use a injected (shared) EntityManagerFactory
and @PersistenceContext annotation Create an EntityManagerFactory like this: EntityManager em =
this.emf.createEntityManager(); Then create and execute your query against
the EntityManagerFactory Add the @Repository annotation to apply
Spring’s exception translation transparently
Spring Annotations
@Component Indicates that a class is a component Class is a candidate for auto-detection
@Controller Specialized component Typically used with request mapping Used in web MVC
@Repository An extension of component generally used for DAO
@Service Intended for business services
@Autowired Marks a constructor, field, setter method for injection
Spring MVC
Model1 Architecture
Spring MVC
Simple to develop Not suitable for large scale applications No easy testability Difficult to maintain an debug issues Can’t modularize code
Spring MVC
MVC = Model View Controller Clearly separates business, navigation
and presentation logic Proven mechanism for a thin, clean web-
tier Model – The data required for the request View – Displays page using the model Controller – Handles the request,
generates model
Front Controller Pattern
Spring MVC
Dispatcher servlet Spring provided front controller Controls the request routing
Controllers User Created POJO Standard spring beans Mapped with Requests
View Responsible for rendering response
Model And View Stores model data Associates a view to the request
View Resolver Used to map logical view names to view implementation
Spring MVC
@Controllerpublic class EventController {
@Autowiredprivate EventDAO eventDAO;
@RequestMappingpublic ModelAndView list() {
ModelAndView mv = new ModelAndView();mv.addObject(“events”, eventDAO.findAll());mv.setViewName(“/events/list”);return mv;
}}
Spring MVC (REST) REST (Reprasentational State Transfer) Architectural style Identifiable Resources
Everything is a resource Resources are accessed by URIs
Uniform interface GET/POST/PUT/DELETE
Stateless conversation No server side session Highly scalable
Resource representations More than one representation (application/xml, text/html, atom …) Desired representation is set in Accept HTTP header
Hypermedia Resources contain links Client state transitions are made through links
Spring MVC
Extends Spring @MVC to handle URL templates - @PathVariable
Leverages Spring OXM module to provide marshalling / unmarshalling (castor,
xstream, jaxb etc) @RequestBody – extract request body to
method parameter @ResponseBody – render return value to response body using converter – no views
required
Spring MVC
@Controller public class AccountController {
@RequestMapping(value="/accounts",method=RequestMethod.GET)
public AccountList getAllAcccount() {
}
@RequestMapping(value="/accounts/${id}",method=RequestMethod.GET)
public Account getAcccount(@PathVariable("id")Long id) {
}
@RequestMapping(value="/accounts/",method=RequestMethod.POST)
public Long createAcccount(@RequestBody Account account) {
}
@RequestMapping(value="/accounts/${id}",method=RequestMethod.PUT)
public Account updateAcccount(@PathVariable("id")Long id, @RequestBody Account account) {
}
@RequestMapping(value="/accounts/${id}",method=RequestMethod.DELETE)
public void deleteAcccount(@PathVariable("id")Long id) {
}
Spring MVC Lab
Configuring Web application Setup JSON & XML Marshallers Setup JSP View resolver REST URIs