Top Banner
Agile Java Development With Spring, Hibernate and Eclipse
117
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Agile Java Dev With Spring Hibernate Eclipse

Agile Java DevelopmentWith Spring, Hibernate and Eclipse

Page 2: Agile Java Dev With Spring Hibernate Eclipse

2

About This Presentation

• Not a tutorial on any one technology!

• Road map for building enterprise-class Java applications … using various “hot” agile methods and simpler Java technologies

Requirements > Design > Code > Monitor

• Downloadable code - Sample “time sheet” application used here

• Note: Working knowledge of Java is expected for this presentation!

Page 3: Agile Java Dev With Spring Hibernate Eclipse

3

Some Material Taken From My Recent Book

Agile Java DevelopmentWith Spring, Hibernate and Eclipse

1. Introduction to Agile Java Development2. The Sample Application: An Online Timesheet System3. XP and AMDD-Based Architecture and Design Modeling4. Environment Setup: JDK, Ant, and JUnit5. Using Hibernate For Persistent Objects6. Overview of the Spring Framework7. The Spring Web MVC Framework8. The Eclipse Phenomenon9. Logging, Debugging, Monitoring and Profiling10. Beyond the Basics11. What Next?12. Parting Thoughts Appendices (with lots of goodies)

available on amazon.com

Forewords by Scott W. Ambler and Rod JohnsonForewords by Scott W. Ambler and Rod Johnson

Page 4: Agile Java Dev With Spring Hibernate Eclipse

4

Book Related Talks

Page 5: Agile Java Dev With Spring Hibernate Eclipse

5

My Background (details at VisualPatterns.com)

• 20 years of experience in the IT Working with Java Technology since late 1995 as a developer,

entrepreneur, author, and trainer. Helped several U.S. based Fortune 100 companies (some smaller

organizations) Published a book and 30 articles Presented at conferences and seminars around the world Awards:

"Outstanding Contribution to the Growth of the Java Community" "Best Java Client" for BackOnline (a Java-based online backup product) Nominated for a Computerworld-Smithsonian award by Scott McNealy

• Founder of: Isavix Corporation – successful IT solutions company (now InScope

Solutions) Isavix Community (now DeveloperHub.com) - award-winning online

developer community (grew to over 100,000 registered members)

• These days: Consultant/Author; details at VisualPatterns.com

Page 6: Agile Java Dev With Spring Hibernate Eclipse

6

Practical Stuff, Not Fluff!

• Recently completed project for U.S. Fortune 50 company

• Application Financial application process billions of $ every week

Clustered application (99.9% uptime required)

Technologies: Spring, Hibernate, JUnit, Ant, Eclipse, etc.

Page 7: Agile Java Dev With Spring Hibernate Eclipse

7

Agenda

1.Introduction to Agile Java Development2.Agile Processes3.Agile Modeling4.Agile Development

Environment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

5.Beyond The Basics

Page 8: Agile Java Dev With Spring Hibernate Eclipse

Introduction to Agile Java Development

Assume simplicity.

Travel light.

- Agile Modeling principles: agilemodeling.com

Assume simplicity.

Travel light.

- Agile Modeling principles: agilemodeling.com

Page 9: Agile Java Dev With Spring Hibernate Eclipse

9

What Is Agile Java Development? It Could Include…

1.Agile Software Processes Iterative Development

Use an Agile method - Scrum, XP, etc.

2.Agile Architecture/Design Modeling Incremental design with “good enough” models Use an agile method - Agile Model Driven Development

(AMDD)

3.Agile Java Design/Development Simple design and coding! Test-driven development (TDD) Efficient frameworks and tools (Ant, JUnit, Hibernate,

Spring, Eclipse…) Plain Old Java Objects (POJOs), whenever possible

Page 10: Agile Java Dev With Spring Hibernate Eclipse

Agile Processes

Requirements change.

Design evolves.

Documents are seldom current.

Requirements change.

Design evolves.

Documents are seldom current.

Page 11: Agile Java Dev With Spring Hibernate Eclipse

Some Stats by The Standish Group (standishgroup.com)

Page 12: Agile Java Dev With Spring Hibernate Eclipse

12

The Solution

CHAOS Ten – Success Factorssource:

standishgroup.com

In 2001, seventeen software pundits came together to unify their methodologies under one umbrella; they jointly defined the term, Agile!

Read story at: martinfowler.com/articles/agileStory.html

In 2001, seventeen software pundits came together to unify their methodologies under one umbrella; they jointly defined the term, Agile!

Read story at: martinfowler.com/articles/agileStory.html

Page 13: Agile Java Dev With Spring Hibernate Eclipse

13

AgileManifesto.org

Page 14: Agile Java Dev With Spring Hibernate Eclipse

14

Term “Agile” Incorporates a Wide Range of Methods

• AM - Agile Modeling• ASD - Adaptive Software Development

• AUP - Agile Unified Process

• Crystal

• FDD - Feature Driven Development

• DSDM - Dynamic Systems Development Method

• Lean Software Development

• Scrum• Xbreed

• XP - eXtreme Programming

• Others…

Page 15: Agile Java Dev With Spring Hibernate Eclipse

“Agility” - All About Smaller Chunks (Shorter/Frequent Cycles)

...Iteration

0Iteration

1Iteration

n

Release 1

...

Release 2

Iteration0

Iteration1

Iterationn

...

softwaresoftware

softwaresoftware softwaresoftware softwaresoftware softwaresoftware softwaresoftware

Incrementally Build Software - Highest Priority Features First!Incrementally Build Software - Highest Priority Features First!

Page 16: Agile Java Dev With Spring Hibernate Eclipse

16

Agile Method: Scrum

• Simple process for product/project management

• Product Backlog - List of known features/changes for product

• Sprint - 1-month iterations (develop highest priority items)

• Meetings Sprint Planning Meeting – Done at beginning of each sprint

(after planning, features moved from product backlog to sprint backlog)

Daily scrum meeting (short: 15 minutes) Sprint review meeting

Page 17: Agile Java Dev With Spring Hibernate Eclipse

17

Agile Method: Extreme Programming (XP)

• Shorter and Frequent Cycles (smaller chunks!) Release - Quarterly Cycles (set a theme) Iteration - Weekly Cycles (e.g. aim for last day of week)

10-minute builds Continuous integration (multiple times per day; manual or automatic)

Incremental Design and Planning (defer investment till needed)

Development in small increments using Test-First development

• Communications - Sit Together, Informative Workspace, on-site customer

• Flow - sustainable pace versus rigid phases; velocity, continuous integration

• Others… visit extremeprogramming.org

Page 18: Agile Java Dev With Spring Hibernate Eclipse

18

Presentation Outline

Introduction to Agile Java Development

Agile Processes

• Agile Modeling

• Agile Development Environment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 19: Agile Java Dev With Spring Hibernate Eclipse

Agile Modeling

“...your goal is to build a shared understanding, it isn’t to write detailed documentation.”

- Scott W. Ambler

“...your goal is to build a shared understanding, it isn’t to write detailed documentation.”

- Scott W. Ambler

Page 20: Agile Java Dev With Spring Hibernate Eclipse

20

Quick Poll

Have you ever been on a project where

documentation was kept up-to-date through end

of project?

Have you ever been on a project where

documentation was kept up-to-date through end

of project?

Page 21: Agile Java Dev With Spring Hibernate Eclipse

Agile Modeling Values, Practices & Principles (agilemodeling.com)

Values Communication, simplicity, feedback, courage and humility. Practices Principles Core Practices: Active Stakeholder Participation Model with Others Apply the Right Artifact(s) Iterate to Another Artifact Prove It with Code Use the Simplest Tools Model in Small Increments Single Source Information Collective Ownership Create Several Models in Parallel Create Simple Content Depict Models Simply Display Models Publicly Supplementary Practices: Apply Modeling Standards Apply Patterns Gently Discard Temporary Models Formalize Contract Models Update Only When It Hurts Really Good Ideas: Refactoring Test-First Design

Core Principles: Model with a Purpose Maximize Stakeholder Investment Travel Light Multiple Models Rapid Feedback Assume Simplicity Embrace Change Incremental Change Quality Work Software Is Your Primary Goal Enabling the Next Effort Is Your Secondary Goal Supplementary Principles: Content Is More Important Than Representation Open and Honest Communication

Page 22: Agile Java Dev With Spring Hibernate Eclipse

"A preliminary work or construction that serves as a plan from which a final product is to be made ... used in testing or perfecting a final product."

"A preliminary work or construction that serves as a plan from which a final product is to be made ... used in testing or perfecting a final product."

Definition Of Word “Model” (freedictionary.com)

Word “model” used to describe diagrams and other artifacts, in this presentation.

Page 23: Agile Java Dev With Spring Hibernate Eclipse

23

Agile Model Driven Development (AMDD)

• Subset of Agile Modeling (agilemodeling.com)

• Agile version of Model Driven Development (MDD)

• Instead of extensive models, “barely good enough”

• Initial modeling activity1. Requirements

2. Architecture

• Requirements modeling Usage models Domain models UI models

• Architecture modeling Free-form diagrams Change cases

Let’s apply this to a sample application, next ...

Let’s apply this to a sample application, next ...

Page 24: Agile Java Dev With Spring Hibernate Eclipse

24

Initiating A New Software Application Project

Page 25: Agile Java Dev With Spring Hibernate Eclipse

25

Problem Statement

Our employees currently submit their weekly hours worked using a paper-based timesheet system that is manually intensive and error-prone.

We require an automated solution for submitting employee hours worked, in the form of an electronic timesheet, approving them, and paying for the time worked.

In addition, we would like to have automatic notifications of timesheet status changes and a weekly reminder to submit and approve employee timesheets.

Our employees currently submit their weekly hours worked using a paper-based timesheet system that is manually intensive and error-prone.

We require an automated solution for submitting employee hours worked, in the form of an electronic timesheet, approving them, and paying for the time worked.

In addition, we would like to have automatic notifications of timesheet status changes and a weekly reminder to submit and approve employee timesheets.

Page 26: Agile Java Dev With Spring Hibernate Eclipse

26

Project Kickoff Meeting

Page 27: Agile Java Dev With Spring Hibernate Eclipse

27

Choices Of Release (High) Level Models

Model with a purpose -- shared understanding!

domain modeldomain model user storiesuser stories UI prototype& flow map

UI prototype& flow map architecturearchitecture

ReleaseLevelModels

scope table,glossary, etc.

scope table,glossary, etc.

CRC cardsCRC cards applicationflow map

applicationflow map

UML diagrams

UML diagrams

databasemodel

databasemodel

IterationLevelModels

acceptancetests

acceptancetests

Page 28: Agile Java Dev With Spring Hibernate Eclipse

28

Sample Scope Table

Shared understanding: what's in and what's out

Shared understanding: what's in and what's out

Scope Functionality Include Time Expression will provide the capability to enter, approve, and

pay for hours worked by employees.

Defer Time Expression will not calculate deductions from paychecks, such as federal/s tate taxes and medical expenses.

Defer Time Expression will not track vacation or sick leave.

Page 29: Agile Java Dev With Spring Hibernate Eclipse

29

Domain Model

Shared understanding: business concepts > key domain objects

Shared understanding: business concepts > key domain objects

Page 30: Agile Java Dev With Spring Hibernate Eclipse

30

User Stories Or Use Cases

Shared understanding: features required of software

Shared understanding: features required of software

3

XP Style User Story Card

Use Case: Login

Author Anil Hemrajani

Description This process allows User to log into the System

Actors/Interfaces FM Trader The System

Trigger User performs a Login action

Preconditions N/A

Success/Basic Flow 1. The System displays the Login panel prompting User for login details as specified in

the 2. User completes all required fields and performs a Submit action.

Failure/A lternative Flow Invalid User ID and/or Password - The system notifies FM trader with the message “Invalid User ID and/or Password”. The system displays the Login panel to User with the contents of all fields empty.

Use Case - Casual, Brief or Fully Dressed

Page 31: Agile Java Dev With Spring Hibernate Eclipse

31

User Interface (UI) Prototype

Shared understanding: functionality, look-and-feel, etc.

Shared understanding: functionality, look-and-feel, etc.

Page 32: Agile Java Dev With Spring Hibernate Eclipse

32

UI Flow Map (Storyboard)

Shared understanding: user interface navigation/flow

Shared understanding: user interface navigation/flow

Page 33: Agile Java Dev With Spring Hibernate Eclipse

33

High-Level Architecture Diagram

Shared understanding: technologies, scalability, security, reliability

Shared understanding: technologies, scalability, security, reliability

BEA WebLogic Server

Objects managed by Spring IoC

Container

HTTP JDBC

ViewJSP/HTML

ControllerSpring

DispatcherServl

et

Web

Browser

ModelBusiness

objects,

Hibernate

beans

SpringScheduler

RDBMS(Oracle)

Page 34: Agile Java Dev With Spring Hibernate Eclipse

34

Shared understanding: common terminology

Shared understanding: common terminology

Glossary - List Of Common Business/Technical Terms

• AccountingThe accounting department/staff.

• ApprovedStatus of a timesheet when a Manager approves a previously submitted timesheet.

• EmployeeA person who works on an hourly basis and reports to a manager.

• PaidStatus of a timesheet when the accounting department has issued a check.

• Etc…

Page 35: Agile Java Dev With Spring Hibernate Eclipse

35

Choices Of Iteration Level (Detailed) Models

domain modeldomain model user storiesuser stories UI prototype& flow map

UI prototype& flow map architecturearchitecture

ReleaseLevelModels

scope table,glossary, etc.

scope table,glossary, etc.

CRC cardsCRC cards applicationflow map

applicationflow map

UML diagrams

UML diagrams

databasemodel

databasemodel

IterationLevelModels

acceptancetests

acceptancetests

Page 36: Agile Java Dev With Spring Hibernate Eclipse

36

Iteration Level Details - Acceptance Tests & Active Stakeholders• Sign In

The employee id can be up to 6 characters. The password must be between 8 and 10 characters.

Only valid users can sign in.

• Timesheet List Only a user's personal timesheets can be accessed.

• Enter Hours Hours must contain numeric data. Daily hours cannot exceed 16 hours. Weekly hours cannot exceed 96 hours.

Hours must be billed to a department. Hours can be entered as two decimal places. Employees can only view and edit their own timesheets.

Page 37: Agile Java Dev With Spring Hibernate Eclipse

37

Exploring Classes Using CRC Cards

Class N am e ( No un)

Responsib ilities ( o b liga tio n s o f th is c la s s , s u c h a s bu s in e s s m e th o ds , e x c e ptio n h a n d lin g , s e c u r ity m e th o ds , a ttr ibu te s / v a r ia b le s ) .

Co llabo rato rs ( o th e r c la s s e s r e qu ir e d to p ro v ide a c o m p le te s o lu tio n to a h igh - le v e l r e qu ir e m e n t)

T im esheetManager

F e tc h e s t im e s h e e t( s ) fr o m da ta ba s e

S a v e s t im e s h e e t to da ta ba s e

T im e s h e e t

T im esheet

K n o w s o f pe r io d e n d in g da te

K n o w s o f t im e

K n o w s o f de pa r tm e n t c o de

domain model

Timesheet List screen

First, let's reflect on what we know, domain model, UI and architecture

Second, let's explore classes on CRC cards using both as input models

T im esheetL istContro ller

C o n tro lle r ( in M V C ) fo r d is p la y in g a lis t o f t im e s h e e ts .

T im e s h e e tM a n a ge r

free-form architecture

Page 38: Agile Java Dev With Spring Hibernate Eclipse

38

Application Flow Map (Home Grown Artifact)

• Complementary to class diagrams and CRC cards

• Can be extended using CRUD columns

Story Tag View Controller Class Collaborators Tables Impacted

Timesheet List

timesheetlist TimeSheetListController TimesheetManager Timesheet

Enter Hours

enterhours EnterHoursController TimesheetManager Timesheet

Department

Page 39: Agile Java Dev With Spring Hibernate Eclipse

39

UML Class and Package Diagrams

Page 40: Agile Java Dev With Spring Hibernate Eclipse

40

Focus Is On Working Software vs. Comprehensive Documentation

Physical Models

CRC cardsCRC cards

applicationflow map

applicationflow map UML

diagrams

UML diagrams

databasemodel

databasemodel

acceptancetests

acceptancetests

Conceptual Models

user storiesuser stories

architecturearchitecture

problemstatement

domain modeldomain modelscopetable

scopetable

glossaryglossary

UI prototype& flow map

UI prototype& flow map

Implementation

Data BaseData Base Code BaseCode Base

THE FINAL AND LASTING ARTIFACTS!

UIprototypes

UIprototypes • Model in Small Increments

• Depict Models Simply

• Discard temporary models

• Prove it with code

- agilemodeling.com

• Model in Small Increments

• Depict Models Simply

• Discard temporary models

• Prove it with code

- agilemodeling.com

Page 41: Agile Java Dev With Spring Hibernate Eclipse

41

Shifting Some Upfront Design to Refactoring

Page 42: Agile Java Dev With Spring Hibernate Eclipse

42

Shifting Some Upfront Design To Refactoring (Continuous Design)• Refactoring is not a new concept; the term is relatively new

• refactoring.com “Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.”- Martin Fowler

Over 100 refactoring techniques; for example: Extract superclass Extract interface Move class Move method

Page 43: Agile Java Dev With Spring Hibernate Eclipse

43

Agile Draw - Elegantly Simple Modeling Technique

UI Flow Map

Conceptual Class Diagram

Visit AgileDraw.org Visit AgileDraw.org

High-Level Architecture

Page 44: Agile Java Dev With Spring Hibernate Eclipse

44

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

• Agile Development Environment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 45: Agile Java Dev With Spring Hibernate Eclipse

Agile Java Development:

Environment Setup (Directory Structure, JDK, Ant, and

JUnit)

Page 46: Agile Java Dev With Spring Hibernate Eclipse

46

Quick Poll

How many of you are using Ant, JUnit,

Maven, Cruise Control, etc?

How many of you are using Ant, JUnit,

Maven, Cruise Control, etc?

Page 47: Agile Java Dev With Spring Hibernate Eclipse

47

Personal Opinion:

Early Environment

Setup Is Essential

Involves more than people expect/plan

Cycle 0• Get minimal environment setup (scripts, directory, version control, etc.)

• Get end-to-end demo working Helps team

Involves more than people expect/plan

Cycle 0• Get minimal environment setup (scripts, directory, version control, etc.)

• Get end-to-end demo working Helps team

Page 48: Agile Java Dev With Spring Hibernate Eclipse

48

Directory Structure, Naming Conventions, Version Control, etc.

➔controller/TimesheetListController.java➔model/Timesheet.java➔model/TimesheetManager.java➔test/TimesheetListControllerTest.java➔test/TimesheetManagerTest.java➔view/timesheetlist.jsp

Page 49: Agile Java Dev With Spring Hibernate Eclipse

© Visual Patterns, Inc. 49

Ant (ant.apache.org)

• Ant task types Compile tasks (that is,

javac) Deployment tasks File tasks such as copy,

delete, move, and others. Property tasks for

setting internal variables

Audit/coverage tasks Database tasks Documentation tasks Execution tasks Mail tasks Preprocess tasks Property tasks Remote tasks Miscellaneous tasks (e.g.

echo)

<ftp server="mirrors.kernel.org" action="get" remotedir="/gnu/chess" userid="anonymous" password="[email protected]" verbose="yes" binary="yes"> <fileset file="README.gnuchess"/></ftp>

<ftp server="mirrors.kernel.org" action="get" remotedir="/gnu/chess" userid="anonymous" password="[email protected]" verbose="yes" binary="yes"> <fileset file="README.gnuchess"/></ftp>

<mail tolist="[email protected]" subject="Hello!" from="[email protected]" mailhost="myhost.com" user="myuserid" password="mypassword"/>

<mail tolist="[email protected]" subject="Hello!" from="[email protected]" mailhost="myhost.com" user="myuserid" password="mypassword"/>

Page 50: Agile Java Dev With Spring Hibernate Eclipse

50

JUnit (junit.org)

• Originally written by Erich Gamma (Gang of Four, Design Patterns) Kent Beck (author of Extreme Programming and Test Driven Development)

• Simple framework – various assert methods assertEquals assertFalse assertNotNull assertNotSame assertNull assertSame assertTrue

public class SimpleTest extends junit.framework.TestCase{ int value1 = 2, value2 = 3, expectedResult = 5;

public static void main(String args[]) { junit.textui.TestRunner.run(suite()); }

public static Test suite() { return new TestSuite(SimpleTest.class); }

public void testAddSuccess() { assertTrue(value1 + value2 == expectedResult); }}

public class SimpleTest extends junit.framework.TestCase{ int value1 = 2, value2 = 3, expectedResult = 5;

public static void main(String args[]) { junit.textui.TestRunner.run(suite()); }

public static Test suite() { return new TestSuite(SimpleTest.class); }

public void testAddSuccess() { assertTrue(value1 + value2 == expectedResult); }}

Page 51: Agile Java Dev With Spring Hibernate Eclipse

51

JUnit GUI Based Testing

Console Runner

Eclipse Plug-in

Page 52: Agile Java Dev With Spring Hibernate Eclipse

52

Agile Method: Test Driven Development (TDD) w/ JUnit• A term coined by Kent Beck

• Also, a XP practice (test-first)

• “Red - Green - Refactor”

• Several benefits to this approach: Minimal code written to satisfy requirements (nothing more, nothing less!) If code passes the unit tests, it is done! Can help design classes better (from a client/interface perspective) Refactor with confidence

Write unit test code

More unit test code

More unit test code

Write some actual code

More actual code

More actual code

Write Test First Code, Compile, Test

Page 53: Agile Java Dev With Spring Hibernate Eclipse

53

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

• Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 54: Agile Java Dev With Spring Hibernate Eclipse

Agile Java Development:

Using Hibernate For Persistent Objects

Page 55: Agile Java Dev With Spring Hibernate Eclipse

55

Quick Poll

What persistence solution does your project use (e.g. JDBC, ORM, entity

bean)?

What persistence solution does your project use (e.g. JDBC, ORM, entity

bean)?

Page 56: Agile Java Dev With Spring Hibernate Eclipse

56

Where Hibernate Fits Into Our Architecture

Page 57: Agile Java Dev With Spring Hibernate Eclipse

57

An Overview of Object-Relational Mapping (ORM)

• ORM - Java object to database table/record mapping Java = objects database = relational

• Relationships unidirectional and bidirectional relations in a relational database are bidirectional by

definition

• Cardinality (OO term is multiciplicity) One-to-one one-to-many many-to-one and many-to-many

• Object Identity

• Cascade

• Others…

Page 58: Agile Java Dev With Spring Hibernate Eclipse

58

Hibernate Basics

• Dialect(DB2, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, SAP DB, Sybase, TimesTen…)

• SessionFactory, Session, and Transaction

• Work with Database Records (as Java Objects)

• Object States - persistent, detached, and transient

• Data Types – more than you'll likely need!

• Hibernate Query Language (HQL) – powerful SQL-like language

Page 59: Agile Java Dev With Spring Hibernate Eclipse

59

From Domain Model To A (Denormalized) Physical Data Model

Page 60: Agile Java Dev With Spring Hibernate Eclipse

60

Working With Hibernate - Simple Example Using Department1.hibernate.cfg.xml – Hibernate configuration file

(DB configuration)<property name="connection.url">

jdbc:hsqldb:hsql://localhost:9005/timex</property><mapping resource="Department.hbm.xml" />

2.Department.hbm.xml – Mapping file for our Department table<class name="com.visualpatterns.timex.model.Department" table="Department"> <id name="departmentCode" column="departmentCode"> <property name="name" column="name"/>

3.Department.java – Bean file with two variables: String departmentCode;

String name;// Setter and getter methods

4.HibernateTest.java – Simple test program (on next slide)

Page 61: Agile Java Dev With Spring Hibernate Eclipse

61

HibernateTest.java

SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory();Session session = sessionFactory.getCurrentSession();

Transaction tx = session.beginTransaction();Department department = (Department)

session.get(Department.class, "IT");

System.out.println("Name for IT = " + department.getName());

...

List departmentList = session.createQuery("from Department").list();for (int i = 0; i < departmentList.size(); i++){ department = (Department) departmentList.get(i); System.out.println("Row " + (i + 1) + "> " + department.getName() + " (" + department.getDepartmentCode() + ")");}

...sessionFactory.close();

Page 62: Agile Java Dev With Spring Hibernate Eclipse

62

Other Hibernate Features

• Saving (save, merge, saveOrUpdate)session.saveOrUpdate(timesheet)

• Deleting records session.delete(Object), or session.createQuery("DELETE from Timesheet")

• Queries using Criteria interface (more OO and typesafe) List timesheetList =

session.createCriteria(Timesheet.class) .add(Restrictions.eq("employeeId", employeeId)) .list();

Related classes: Restrictions, Order, Junction, Distinct, and others

• Locking Objects (Concurrency Control)

• Lots More Hibernate (associtions, annotations, filters, interceptors, scrollable iterations, native SQL, transaction management, etc.)

Page 63: Agile Java Dev With Spring Hibernate Eclipse

63

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

• Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 64: Agile Java Dev With Spring Hibernate Eclipse

Agile Java Development:

The Spring Framework

Page 65: Agile Java Dev With Spring Hibernate Eclipse

65

Spring Modules

Page 66: Agile Java Dev With Spring Hibernate Eclipse

66

Spring Java Packaging (org.springframework.)

Page 67: Agile Java Dev With Spring Hibernate Eclipse

Quick Poll

Are you familiar with Inversion of Control

(IoC)?

Are you familiar with Inversion of Control

(IoC)?

Page 68: Agile Java Dev With Spring Hibernate Eclipse

68

• Dependency Injection Styles Two Supported By Spring:

Setter/getter based Constructor based

Fowler suggests a 3rd, interface injection, http://www.martinfowler.com/articles/injection.html

• Spring IoC Concepts: Beans, BeanFactory, ApplicationContext…

IoC Container And Dependency Injection Pattern

public class A{ B myB = new B(); C myC = new C();}

public class A{ public setB(B myB) public setC(C myC)Class A

Class CClass B

IOCContainer

Normal Way Using IoC

Page 69: Agile Java Dev With Spring Hibernate Eclipse

69

Benefits of Using Spring

• Light weight Inversion of Control (IoC) container

• Excellent support for POJOs (e.g. declarative transaction management)

• Modular – not an all-or-nothing approach

• Testing – dependency injection and POJOs makes for easier testing

• Many others No Singletons Builds on top of existing technologies (e.g. JEE, Hibernate)

Robust MVC web framework Consistent database exception hierarchy (e.g. wrap SQLException)

Page 70: Agile Java Dev With Spring Hibernate Eclipse

70

Where Spring Framework Fits Into Our Architecture

OptionalHibernate integration

Page 71: Agile Java Dev With Spring Hibernate Eclipse

71

Quick Poll

Which web framework do you use?

Which web framework do you use?

Page 72: Agile Java Dev With Spring Hibernate Eclipse

72

Spring Web MVC

• Easier testing – mock classes, dependency injection

• Bind directly to business objects

• Clear separation of roles – validators, adaptable controllers, command (form) object, etc.

• Simple but powerful tag libraries

• Support for various view technologies and web frameworks (e.g. Struts, webwork, tapestry, JSF)

Page 73: Agile Java Dev With Spring Hibernate Eclipse

73

Spring MVC Java Concepts

1.Controller

2.ModelAndView

3.Command (Form Backing) Object

4.Validator

5.Spring Tag Library (spring:bind)

Page 74: Agile Java Dev With Spring Hibernate Eclipse

74

<bean id="urlMapAuthenticate” class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <prop key="/enterhours.htm">enterHoursController</prop>...

<bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property></bean>

<bean id="urlMapAuthenticate” class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <prop key="/enterhours.htm">enterHoursController</prop>...

<bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property></bean>

Spring MVC Configuration

<servlet> <servlet-name>timex</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>timex</servlet-name> <url-pattern>*.htm</url-pattern></servlet-mapping>

<servlet> <servlet-name>timex</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>timex</servlet-name> <url-pattern>*.htm</url-pattern></servlet-mapping>

timex-servlet.xml

web.xml

Page 75: Agile Java Dev With Spring Hibernate Eclipse

75

Sample End-To-End Flow Using Spring and Hibernate

Page 76: Agile Java Dev With Spring Hibernate Eclipse

76

Timesheet List: A No-Form Controller Example

public class TimesheetListController implements Controller {... public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response)

mockHttpServletRequest = new MockHttpServletRequest("GET", "/timesheetlist.htm");ModelAndView modelAndView = timesheetListController.handleRequest( mockHttpServletRequest, null);

assertNotNull(modelAndView);assertNotNull(modelAndView.getModel());

mockHttpServletRequest = new MockHttpServletRequest("GET", "/timesheetlist.htm");ModelAndView modelAndView = timesheetListController.handleRequest( mockHttpServletRequest, null);

assertNotNull(modelAndView);assertNotNull(modelAndView.getModel());

Page 77: Agile Java Dev With Spring Hibernate Eclipse

77

Enter Hours: A Form Screen

public class EnterHoursController extends SimpleFormControllerpublic class EnterHoursController extends SimpleFormController

1. EnterHoursController.java2. EnterHoursValidator.java3. enterhours.jsp

Page 78: Agile Java Dev With Spring Hibernate Eclipse

78

View/JSP Code – Spring and JSTL Tag Libraries

<spring:bind path="command.employeeId"> <input name='<c:out value="${status.expression}"/>' value='<c:out value="${status.value}"/>' type="text" size="6" maxlength="6"></spring:bind>

<spring:bind path="command.employeeId"> <input name='<c:out value="${status.expression}"/>' value='<c:out value="${status.value}"/>' type="text" size="6" maxlength="6"></spring:bind>

Special (Spring) variable named status• status.value• status.expression• status.error• status.errorMessage• status.errorMessages• status.displayValue

Page 79: Agile Java Dev With Spring Hibernate Eclipse

79

public class HttpRequestInterceptor extends HandlerInterceptorAdapter{ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!signedIn) { response.sendRedirect(this.signInPage); return false; }

public class HttpRequestInterceptor extends HandlerInterceptorAdapter{ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!signedIn) { response.sendRedirect(this.signInPage); return false; }

Sign In (Authentication) - Spring HandlerInterceptor

Page 80: Agile Java Dev With Spring Hibernate Eclipse

80

Other Spring Web Stuff

• View with no controllers (e.g. only JSP files)<bean id="urlFilenameController"

class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/><prop key="/help.htm">urlFilenameController</prop>

• Spring 2.0 – new tag libraries form:form - org.springframework.web.servlet.tags.form.FormTag form:input- org.springframework.web.servlet.tags.form.InputTag form:password -

org.springframework.web.servlet.tags.form.PasswordInputTag form:hidden -

org.springframework.web.servlet.tags.form.HiddenInputTag form:select -

org.springframework.web.servlet.tags.form.SelectTag form:option -

org.springframework.web.servlet.tags.form.OptionTag form:radiobutton -

org.springframework.web.servlet.tags.form.RadioButtonTag Others…

• Other Web Flow – gaining a lot of momentum! Wizard-like features.

Portlet API – based on JSR-168 Portlet Specification (jcp.org).

Page 81: Agile Java Dev With Spring Hibernate Eclipse

81

Spring ORM Module: Support for Hibernate

• Management of sessionfactory and session (no close calls)

• Declarative transaction management in light-weight containers

• Easier testing (pluggable Sessionfactory via XML file)

• Less lines of code – focus on business logic!

Page 82: Agile Java Dev With Spring Hibernate Eclipse

82

Spring ORM Module: Support for Hibernate (cont’d)

Less lines of code

File Programmatic Declarative DepartmentManager.java 39 22 EmployeeManager.java 66 36 TimesheetManager.java 166 87 TOTAL 271 145

Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();try{ session.saveOrUpdate(timesheet); session.getTransaction().commit();}catch (HibernateException e){ session.getTransaction().rollback(); throw e;}

Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();try{ session.saveOrUpdate(timesheet); session.getTransaction().commit();}catch (HibernateException e){ session.getTransaction().rollback(); throw e;}

getHibernateTemplate().saveOrUpdate(timesheet);getHibernateTemplate().saveOrUpdate(timesheet);

Page 83: Agile Java Dev With Spring Hibernate Eclipse

83

More Spring…

• Scheduling Jobs (with Quartz or JDK timers)

• Spring email support

• Much more JEE support Sub-projects (Acegi, BeanDoc, Spring IDE, etc.)

<bean id="reminderEmailJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="reminderEmail" /> <property name="targetMethod" value="sendMail" /></bean>

<bean id="reminderEmailJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="reminderEmailJobDetail" /> <property name="cronExpression" value="0 0 14 ? * 6" /></bean>

<bean id="reminderEmailJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="reminderEmail" /> <property name="targetMethod" value="sendMail" /></bean>

<bean id="reminderEmailJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="reminderEmailJobDetail" /> <property name="cronExpression" value="0 0 14 ? * 6" /></bean>

Page 84: Agile Java Dev With Spring Hibernate Eclipse

84

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

• Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects

The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 85: Agile Java Dev With Spring Hibernate Eclipse

Agile Java Development:

The Eclipse Phenomenon!

Page 86: Agile Java Dev With Spring Hibernate Eclipse

86

Quick Poll

Which IDE do you use?Which IDE do you use?

Page 87: Agile Java Dev With Spring Hibernate Eclipse

87

The Eclipse Foundation, Platform and Projects

• Foundation Originally developed by Object Technology International (OTI), purchased by IBM ($40 million) and donated it to open source!

Recruited various corporations; from eclipse.org: Industry leaders Borland, IBM, MERANT, QNX Software Systems, Rational Software, Red Hat, SuSE, TogetherSoft and Webgain formed the initial eclipse.org Board of Stewards in November 2001. By the end of 2003, this initial consortium had grown to over 80 members.

My view: Eclipse foundation is similar to Apache foundation for GUI tools

• Platform objectives robust platform for highly integrated dev tools enable view and/or editing of any content type attract a large community of developers to develop plug-ins

• ProjectsApplication Development, editors, modeling, performance, testing, reporting, and many more

Page 88: Agile Java Dev With Spring Hibernate Eclipse

88

Personal Opinion:

The Java versus

Microsoft Thing

First exciting IDE Huge community - Plug-ins galore

(thousand+) Ward Cunningham and Erich Gamma Battle of IDEs has only now begun!

First exciting IDE Huge community - Plug-ins galore

(thousand+) Ward Cunningham and Erich Gamma Battle of IDEs has only now begun!

Page 89: Agile Java Dev With Spring Hibernate Eclipse

89

How Eclipse Can Help With Our Application

Page 90: Agile Java Dev With Spring Hibernate Eclipse

90

Eclipse Basic Concepts

1. Workspace (directory of projects)

2. Workbench3. Perspectives4. Editors and Views5. Project6. Wizards (hundreds)

7. Plug-ins (galore!)

sample workspace

Page 91: Agile Java Dev With Spring Hibernate Eclipse

91

Eclipse Plug-in: Java Development Tools (JDT)

Ant Assist

Java Browsing

Java Compile Errors/Warnings

JUnit

Page 92: Agile Java Dev With Spring Hibernate Eclipse

92

JDT: Other Notable Features

• Compile during save (within the blink of an eye)

• Formatting options

• Scrapbook

• TODO lists

• Others Powerful search Code refactoring (some based on Fowler's refactoring.com)

Export feature (create zip files, etc.)

Page 93: Agile Java Dev With Spring Hibernate Eclipse

93

Eclipse Plug-In: Web Tools Platform (WTP; eclipse.org)

• Tools for developing JEE Web applications

• Editors Source - HTML, JavaScript, CSS, JSP, SQL, XML, DTD, XSD, and WSDL

Graphical - XSD and WSDL

• Database access and query tools and models

• Web service wizards

• Other JEE features (EJB, JSP, Servlet…)

• Much more…

Page 94: Agile Java Dev With Spring Hibernate Eclipse

94

WTP: Notable Features

Database

ServersJSP Assist

Web Services

Page 95: Agile Java Dev With Spring Hibernate Eclipse

95

CVS (Eclipse Team Sharing)

Page 96: Agile Java Dev With Spring Hibernate Eclipse

96

Hibernate and Spring Plug-Ins

Hibernate

Spring IDE

Page 97: Agile Java Dev With Spring Hibernate Eclipse

97

Startup Time Comparison To IntelliJ and NetBeans

IntellIJ - 1 minute, 5 seconds!

Eclipse with JDT, WTP, Hibernate, Eclipse... 19 seconds!

Eclipse with JDT, WTP, Hibernate, Eclipse... 19 seconds!

NetBeans - 42 seconds.

Page 98: Agile Java Dev With Spring Hibernate Eclipse

98

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

• Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects

The Spring Framework

The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 99: Agile Java Dev With Spring Hibernate Eclipse

Agile Java Development:

Logging, Debugging, Monitoring, and Profiling

Page 100: Agile Java Dev With Spring Hibernate Eclipse

100

Quick Poll

Do you use a GUI debugger? Or, a logging framework?

Or, use println statements?

Do you use a GUI debugger? Or, a logging framework?

Or, use println statements?

Page 101: Agile Java Dev With Spring Hibernate Eclipse

101

Logging Basics and Frameworks

• Types1.Audit log2.Tracing3.Error reporting

• Pros• No human intervention (automated)

• Great for head-less servers

• Cons• Performance hit

• Can clutter code

import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;

public class CommonsLoggingTest{ private static Log log = LogFactory.getLog(CommonsLoggingTest.class);

public static void main(String[] args) { log.fatal("This is a FATAL message."); log.error("This is an ERROR message."); log.warn("This is a WARN message."); log.info("This is an INFO message."); log.debug("This is a DEBUG message."); }}

Logging Frameworks

• Alternative to println statements

• Key benefit - Output control (destination, format, log level)

• Most popular - Apache Log4J and JDK Logging

• Jakarta Commons Logging -- bridge to frameworks

Page 102: Agile Java Dev With Spring Hibernate Eclipse

102

Headaches of Finding and Fixing Bugs!

Page 103: Agile Java Dev With Spring Hibernate Eclipse

103

Debugging Java Code With Eclipse

• Debug perspectives

and views

• Breakpoints

• Step through code

• Variable inspection

• Hotswap

• Remote debugging

“consolidated debugging”

Page 104: Agile Java Dev With Spring Hibernate Eclipse

104

Debugging Web User Interfaces Using Mozilla Firefox

JavaScript debugger

Web Developer

Tamper Data

Page 105: Agile Java Dev With Spring Hibernate Eclipse

105

Java Monitoring and Profiling

• Monitoring JSE 5.0 includes JConsole

Memory issues Class loading and garbage collection

Management of MBeans and JDK logging level, etc …

• Profiling Memory usage and leaks

CPU utilization Trace objects and methods

Determine performance bottlenecks

<bean id="timexJmxBean” class= "com.visualpatterns.timex.util.TimexJmxBean" />

<bean id="exporter” class= "org.springframework.jmx.export.MBeanExporter"> <property name="beans"> <map> <entry key="Time Expression:name=timex-stats" value-ref="timexJmxBean" />

<bean id="timexJmxBean” class= "com.visualpatterns.timex.util.TimexJmxBean" />

<bean id="exporter” class= "org.springframework.jmx.export.MBeanExporter"> <property name="beans"> <map> <entry key="Time Expression:name=timex-stats" value-ref="timexJmxBean" />

Spring MBean Exporter

Page 106: Agile Java Dev With Spring Hibernate Eclipse

106

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects

The Spring Framework

The Eclipse Phenomenon!

Logging, Debugging, Monitoring, and Profiling

• Beyond The Basics

Page 107: Agile Java Dev With Spring Hibernate Eclipse

Beyond The Basics

Page 108: Agile Java Dev With Spring Hibernate Eclipse

108

Security, Reliability and Scalability Considerations

Page 109: Agile Java Dev With Spring Hibernate Eclipse

109

Application Security Considerations

• Authentication (user and application levels)

• Authorization (roles, groups, etc.)

• Encryption (wire protocol, configuration files)

Wire protocol (HTTP/S)

User-level authenticati

on & authorizatio

n

Application-level

authentication

Page 110: Agile Java Dev With Spring Hibernate Eclipse

110

Other Considerations

• Exception Handling1.Checked exceptions (e.g. IOException) – required catch or throw

2.Unchecked exceptions (e.g. NullPointerException) - no catch/throw needed

3.Errors (e.g. OutOfMemoryError)

• Clustering (serialize, no static variables, simplicity…)

• Multi-threading (JDK 1.5 concurrent API)

• Rich Internet Applications (RIA) AJaX -

Google Web Toolkit (GWT) - http://code.google.com/webtoolkit/

Direct Web Remoting (DWR) - http://getahead.ltd.uk/dwr/

Adobe Flex Java Swing and Web Start

Page 111: Agile Java Dev With Spring Hibernate Eclipse

111

Cool Concept For Smaller Apps - Entire System In A WAR File!• Code (source, binary)

• Relational database (e.g. HSQLDB)

• Job Scheduling

• More…

Page 112: Agile Java Dev With Spring Hibernate Eclipse

Wrap Up!

Page 113: Agile Java Dev With Spring Hibernate Eclipse

Presentation Outline

Introduction to Agile Java Development

Agile Processes

Agile Modeling

Agile DevelopmentEnvironment Setup: Directory Structure, JDK, Ant and JUnit

Using Hibernate For Persistent Objects

The Spring Framework

The Eclipse Phenomenon!

Logging, Debugging, Monitoring, and Profiling

Beyond The Basics

Page 114: Agile Java Dev With Spring Hibernate Eclipse

114

Constant Learning – Be a “Generalizing Specialist”

“A generalizing specialist is someone with a good grasp of how everything fits together.”

- agilemodeling.com

“A generalizing specialist is someone with a good grasp of how everything fits together.”

- agilemodeling.com

Page 115: Agile Java Dev With Spring Hibernate Eclipse

115

Most Important… Don’t Forget To Have Fun! :-)

RONRON STEVESTEVE RAJRAJ SUSANSUSAN

Page 116: Agile Java Dev With Spring Hibernate Eclipse

116

THE END!

• agilemodeling.com

• agiledata.org

• agilemanifesto.org

• extremeprogramming.org

• hibernate.org

• springframework.org

• eclipse.org

• code.google.com/webtoolkit/

• getahead.ltd.uk/dwr/

Page 117: Agile Java Dev With Spring Hibernate Eclipse

Thank you!