790 likes | 988 Views
DEVELOPING ENTERPRISE APPLICATIONS SPRING, 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
E N D
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 Persistance Interaction JDBC Persistance Custom Direct JDBC access code RDBMS Java Application (Swing, JSP, Beans etc…) POJO JPA Hibernate
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 JDBC JPA ORM Object 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 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 //query List<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 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 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” • “Autowiring” • 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"/>