Agile Java Dev With Spring Hibernate Eclipse

download Agile Java Dev With Spring Hibernate Eclipse

of 119

Transcript of Agile Java Dev With Spring Hibernate Eclipse

Agile Java DevelopmentWith Spring, Hibernate and EclipseAnil [email protected]

Visual Patterns, Inc.

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!

Visual Patterns, Inc.

2

Some Material Taken From My Recent Book

Agile Java DevelopmentWith Spring, Hibernate and EclipseForewords by Scott W. Ambler and Rod Johnson

available on amazon.com

1. Introduction to Agile Java Development 2. The Sample Application: An Online Timesheet System 3. XP and AMDD-Based Architecture and Design Modeling 4. Environment Setup: JDK, Ant, and JUnit 5. Using Hibernate For Persistent Objects 6. Overview of the Spring Framework 7. The Spring Web MVC Framework 8. The Eclipse Phenomenon 9. Logging, Debugging, Monitoring and Profiling 10. Beyond the Basics 11. What Next? 12. Parting ThoughtsAppendices (with lots of goodies)

Visual Patterns, Inc.

3

Book Related Talks

Visual Patterns, Inc.

4

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 articlesPresented 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 Visual Patterns, Inc.

5

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.

Visual Patterns, Inc.

6

Agenda

1. 2. 3. 4.

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

5. Beyond The Basics

Visual Patterns, Inc.

7

Introduction to Agile Java Development

Assume simplicity. Travel light. - Agile Modeling principles: agilemodeling.com

Visual Patterns, Inc.

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

Visual Patterns, Inc.

9

Agile Processes

Requirements change. Design evolves. Documents are seldom current.

Visual Patterns, Inc.

Some Stats by The Standish Group (standishgroup.com)

Visual Patterns, Inc.

The Solution

CHAOS Ten Success Factors source: 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 Visual Patterns, Inc.

12

AgileManifesto.org

Visual Patterns, Inc.

13

Term Agile Incorporates a Wide Range of Methods

AM - Agile Modeling ASD - Adaptive Software Development AUP - Agile Unified Process

CrystalFDD - Feature Driven Development DSDM - Dynamic Systems Development Method

Lean Software Development

Scrum Xbreed

XP - eXtreme Programming Others Visual Patterns, Inc.

14

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

Release 1Iteration 0 Iteration 1

Release 2

...

Iteration n

Iteration 0

Iteration 1

...

Iteration n

...

Incrementally Build Software - Highest Priority Features First!

software

software

software

software

software

software

Visual Patterns, Inc.

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

Visual Patterns, Inc.

16

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, onsite customer

Flow - sustainable pace versus rigid phases; velocity, continuousintegration

Others visit extremeprogramming.org Visual Patterns, Inc.

17

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

Visual Patterns, Inc.

18

Agile Modeling...your goal is to build a shared understanding, it isnt to write detailed documentation.

- Scott W. Ambler

Visual Patterns, Inc.

Quick Poll

Have you ever been on a project where documentation was kept up-to-date through end of project?

Visual Patterns, Inc.

20

Agile Modeling Values, Practices & Principles (agilemodeling.com)ValuesCommunication, sim plic it y, feedback, courage and humili ty.

PracticesCore Practices: Active Stakeholder Participat ion Model with Others Apply the Right Artifact(s) Iterate to Another Artifact Prove It with Code Use the Simplest Tools Model in Small Incr ements Single Source Informatio n Colle ctive Ownership Create Several Models in Paral lel Create Sim ple Content Depict Models Simply Displa y Models Public ly Supplementary Practices: Apply Modeling Standards Apply Patterns Gently Discar d Temporary Models Formali ze Contract Models Update Only When It Hurts Really Good Ideas: Refactoring Test-Fir st Design

PrinciplesCore Princip les: Model with a Purpose Maximize Stakeholder Investment Travel Light Mult iple 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

Visual Patterns, Inc.

Definition Of Word Model (freedictionary.com)

"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."Word model used to describe diagrams and other artifacts, in this presentation.

Visual Patterns, Inc.

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

Requirements Architecture

Requirements modeling

Usage models Domain models UI models

Architecture modeling

Free-form diagrams Change cases Visual Patterns, Inc.

Lets apply this to a sample application, next ...23

Initiating A New Software Application Project

Visual Patterns, Inc.

24

Problem Statement

Our employees currently submit their weekly hours worked using a paper-based timesheet system that is manually intensive and errorprone. 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.

Visual Patterns, Inc.

25

Project Kickoff Meeting

Visual Patterns, Inc.

26

Choices Of Release (High) Level Models

Release Level Models

scope table, glossary, etc.

domain model

user stories

UI prototype & flow map

architecture

Iteration Level Models

acceptance tests

CRC cards

application flow map

UML diagrams

database model

Model with a purpose -- shared understanding!

Visual Patterns, Inc.

27

Sample Scope Table

Scope Functionality Include Time Expression will provide the capability to enter, approve, and pay for hours worked by employees. Defer Defer Time Expression will not calculate deductions from paychecks, such as federal/state taxes and medical expenses. Time Expression will not track vacation or sick leave.

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

Visual Patterns, Inc.

28

Domain Model

Shared understanding: business concepts > key domain objects Visual Patterns, Inc.

29

User Stories Or Use Cases3Use Case: LoginAuthor Anil Hemrajani DescriptionThis process allows User to log into the System

XP Style User Story Card

Actors/Interfaces FM Trader The System

Trigger User performs a Login actionPreconditions N/A

Success/Basic Flow 1. The System displays the Login panel p rompting User for login details as specified in the 2. User completes all required fields and performs a Submit action. Failure/Alternative Fl owInvalid 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

Shared understanding: features required of software Visual Patterns, Inc.

30

User Interface (UI) Prototype

Shared understanding: functionality, look-and-feel, etc. Visual Patterns, Inc.

31

UI Flow Map (Storyboard)

Shared understanding: user interface navigation/flow Visual Patterns, Inc.

32

High-Level Architecture Diagram

Web Browser

HTTP

ControllerSpring

ModelBusiness objects,Hibernate beans

JDBC

RDBMS(Oracle)

DispatcherServlet

ViewJSP/HTML

Spring Scheduler

Objects managed by Spring IoC Container

BEA WebLogic Server

Shared understanding: technologies, scalability, security, reliability Visual Patterns, Inc.

33

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.

EtcShared understanding: common terminology Visual Patterns, Inc.

34

Choices Of Iteration Level (Detailed) Models

Release Level Models

domain model CRC cards

user stories

UI prototype & flow map

architecture

scope table, glossary, etc.

Iteration Level Models

acceptance tests

application flow map

UML diagrams

database model

Visual Patterns, Inc.

35

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. Only a user's personal timesheets can be accessed. 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.

Timesheet List

Enter Hours

Visual Patterns, Inc.

36

Exploring Classes Using CRC CardsFirst, let's reflect on what we know,domain model, UI and architecture

Second, let's explore classes on CRCcards using both as input modelsClass Name (Noun) Responsibilities (obligations of this class, such as business methods, exception handling, security methods, attributes/variables). Collaborators (other classes required to provide a complete solution to a high -level requirement)

Timesheet List screen

TimesheetListController Controller (in MVC) for displaying a list of timesheets.TimesheetManagerfree-form architecture

TimesheetManager

Fetches timesheet(s) from database Saves timesheet to database

Timesheet

Timesheet Knows of period ending datedomain model

Knows of time Knows of department code Visual Patterns, Inc.

37

Application Flow Map (Home Grown Artifact)

Complementary to class diagrams and CRC cards Can be extended using CRUD columns

Story Tag Timesheet List Enter Hours

View timesheetlist enterhours

Controller Class TimeSheetListController EnterHoursController

Colla borators TimesheetManager TimesheetManager

Tables Impacted Timesheet Timesheet Department

Visual Patterns, Inc.

38

UML Class and Package Diagrams

Visual Patterns, Inc.

39

Focus Is On Working Software vs. Comprehensive DocumentationConceptual Models

problem statement

domain model user stories UI prototypes architecture

scope table

Model in Small Increments Depict Models Simply

glossary

Physical Models

acceptance tests

CRC cards

database model

Discard temporary models Prove it with code

application flow map

UML diagrams

- agilemodeling.com

Implementation

THE FINAL AND LASTING ARTIFACTS!

Data Base

UI prototype Code Base & flow map

Visual Patterns, Inc.

40

Shifting Some Upfront Design to Refactoring

Visual Patterns, Inc.

41

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

Visual Patterns, Inc.

42

Agile Draw - Elegantly Simple Modeling Technique

High-Level Architecture UI Flow Map

Visit AgileDraw.orgConceptual Class Diagram43

Visual Patterns, Inc.

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

Visual Patterns, Inc.

44

Agile Java Development: Environment Setup (Directory Structure, JDK, Ant, and JUnit)

Visual Patterns, Inc.

Quick Poll

How many of you are using Ant, JUnit, Maven, Cruise Control, etc?

Visual Patterns, Inc.

46

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 team47

Visual Patterns, Inc.

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

Visual Patterns, Inc.

48

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 tasksMiscellaneous tasks (e.g. echo)

Visual Patterns, Inc.

49

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

}

Visual Patterns, Inc.

50

JUnit GUI Based Testing

Console Runner

Eclipse Plug-in Visual Patterns, Inc.

51

Agile Method: Test Driven Development (TDD) w/ JUnit A term coined by Kent Beck Also, a XP practice (test-first) Red - Green - Refactor

Write Test FirstWrite unit test code More unit test code More unit test code

Code, Compile, TestWrite some actual code More actual code More actual code

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

Visual Patterns, Inc.

52

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

Visual Patterns, Inc.

53

Agile Java Development: Using Hibernate For Persistent Objects

Visual Patterns, Inc.

Quick Poll

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

Visual Patterns, Inc.

55

Where Hibernate Fits Into Our Architecture

Visual Patterns, Inc.

56

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-oneone-to-many many-to-one and many-to-many

Object Identity Cascade Others Visual Patterns, Inc.

57

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 Visual Patterns, Inc.

58

From Domain Model To A (Denormalized) Physical Data Model

Visual Patterns, Inc.

59

Working With Hibernate - Simple Example Using Department

1. hibernate.cfg.xml Hibernate configuration file (DBconfiguration) jdbc:hsqldb:hsql://localhost:9005/timex

2. Department.hbm.xml Mapping file for our Department table

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) Visual Patterns, Inc.

60

HibernateTest.javaSessionFactory 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();

Visual Patterns, Inc.

61

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.) Visual Patterns, Inc.

62

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

Visual Patterns, Inc.

63

Agile Java Development: The Spring Framework

Visual Patterns, Inc.

Spring Modules

Visual Patterns, Inc.

65

Spring Java Packaging (org.springframework.)

Visual Patterns, Inc.

66

Quick Poll

Are you familiar with Inversion of Control (IoC)?

Visual Patterns, Inc.

IoC Container And Dependency Injection PatternNormal Waypublic class A { B myB = new B(); C myC = new C(); }

Using IoCClass BIOC Container

Class C

Class A

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

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 Visual Patterns, Inc.

68

Benefits of Using Spring

Light weight Inversion of Control (IoC) container Excellent support for POJOs (e.g. declarative transactionmanagement)

Modular not an all-or-nothing approach

Testing dependency injection and POJOs makes for easiertesting

Many others

No SingletonsBuilds on top of existing technologies (e.g. JEE, Hibernate) Robust MVC web framework Consistent database exception hierarchy (e.g. wrap SQLException) Visual Patterns, Inc.

69

Where Spring Framework Fits Into Our Architecture

Optional Hibernate integration

Visual Patterns, Inc.

70

Quick Poll

Which web framework do you use?

Visual Patterns, Inc.

71

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)

Visual Patterns, Inc.

72

Spring MVC Java Concepts

1. Controller 2. ModelAndView 3. Command (Form Backing) Object 4. Validator 5. Spring Tag Library (spring:bind)

Visual Patterns, Inc.

73

Spring MVC Configuration timex org.springframework.web.servlet.DispatcherServlet 1 timex *.htm

web.xml

timex-servlet.xml