If you can't read please download the document
Upload
carol-mcdonald
View
3.652
Download
4
Embed Size (px)
DESCRIPTION
comparing and application build using JavaEE, Java EE with Spring, or JavaEE with SEAM
Citation preview
2. About the Speaker
3. Agenda
4. Sample Application 5. Catalog Java EEApplication
DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean 6. JPA Unifying/Standardizing Persistence
7. JPA: Simplifying/Unifying/Standardizing Persistence
8. Entity Annotated as Entity @Id denotes primary key Getters/setters to access state @Entity public class Item implements Serializable { @Idprotected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimalname){this.price=price;} } 9. Simple Mapping Mapping defaultsto matchingcolumn name . Onlyconfigure ifentity field and table column names aredifferent public class Item {int id; String name;String description; String url ; } @Entity @Column(name=DESC) @Id Item ID NAME DESC URL 10. Relationships JPA Standardized O/R Mapping
Relationships 11. Relationship Mappings OneToMany Bidirectional public classProduct{ int id; ... Collection items; } public classItem{ int id; ... Product product; } @Entity @Entity @OneToMany( mappedBy = product ) @ManyToOne @Id @Id 1 n has to saywhere the foreign key isusingmappedBy Item ID PROD_ID PRODUCT ID . . . 12. PersistenceContext EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() EntityManagerAPI to manipulate entities Set of managed entities Interface thru which applications interact with the entities and the persistence engine Servlets EJBs Java app 13. How Does it Work? Entity Manager
14. Persistence Context
15. Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Session Facade Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence ContextPropagated Transaction Attributes 2. Create Order 16. Persistence Context- Transactional vs. Extended @Stateless public class OrderSessionStateless implements OrderService { @PersistenceContext(unitName=java_one) EntityManager em;public voidaddLineItem (OrderLineItem li){// First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class OrderSessionStateful implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em; // Order is a member variable Loaded from the db in lookupOrder Order order public voidaddLineItem (OrderLineItem li){ // No em.find invoked for the order objectorder.lineItems.add(li); } 17. Catalog Java EEApplication
DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean 18. Business Interface
CatalogServiceBusiness Interface 19. Catalog Stateless Session EJB, JPA Query@Stateless public classCatalogimplementsCatalogService{ @PersistenceContext(unitName=PetCatalogPu) EntityManager em; @TransactionAttribute(NOT_SUPPORTED) public ListgetItems (intfirstItem , intbatchSize ) {Queryq =em . createQuery (" select i from Item as i ");q. setMaxResults ( batchSize ); q. setFirstResult ( firstItem ); List items= q.getResultList(); return items;} } 20. Java EE: Dependency Injection
21. Agenda
22. JSFComponent, EventDrivenWeb Framework
View Root Form id=guess Managed Bean getUserNumber() setUserNumber(..) guess() Business Service guess()
UIIputid=guessNum UICommandid=submit 23. What is a JSF UI Component? Some Standard Components 24. Some Open Source UI Components 25. UI Components
maintains component state, processes input renders a user interface Component Class XML Tag Renderer 26. JSF Web FrameworkView Controller Model Request ServiceInterface Events 27. Catalog Java EEApplication
DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean 28. List ItemspageData Table 29. list.jsp
30. Binding UI to Managed Bean
ItemController.java public classItemController ... public longgetItems(){
Managed Bean property 31. Managed Bean Value Binding
GET SET 32. list.jspPage < h:dataTablevalue='#{ itemController.items }'var=' dataTableItem '> value='Name'/> < h:commandLinkaction='#{item.detailSetup}' value='#{ dataTableItem .name}'/> ... < h:graphicImageurl='#{ dataTableItem .imagethumburl}'/> ... < h:outputTextvalue='#{ dataTableItem .price}'/> ... 33. UIComponents Bindingto a Managed Bean
Managed Bean property Managed Bean
Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page 34. Managed Bean: ItemController
35. Catalog Stateless Session EJB@Stateless public class Catalog implements CatalogService { @PersistenceContext(unitName=PetCatalogPu) EntityManager entityManager; @TransactionAttribute(NOT_SUPPORTED) public ListgetItems (int firstItem, int batchSize) {Queryq = em. createQuery (" select i from Item as i ");q. setMaxResults (batchSize); q. setFirstResult (firstItem); List items= q.getResultList(); return items;} } 36. Relationship Between Objects getItems() viaEntityBean 1 m #{itemController.items} Item Entity Product Entity Catalog StatelessSB Item Controller list.jsp 37. List ItemspageLink to see Item Details JSF is event-driven,listens for actions 38. list.jsp
Click causes Action Event JSF is event-driven,listens for actions 39.
JSF Standard request processing lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
JSF is event-driven,listens for actions 40. JSF Actions
41. Navigation Example from-view to-view from-outcome list.jsp new_usr.jsp error.jsp error.jsp detail.jsp item_detail new user error 42. Navigation
< h: commandLink action ="#{ itemController.detailSetup } /> 43. Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations 44. Item Detail Page 45. detail.jsp
Calls itemController.getItem().getName() 46. UIOutput component value attribute
Calls itemController.getItem().getName() 47. Get Next List of Itemspage 48. Invoke Application Phase
49. Navigation
< h: commandLink action ="#{ itemController.next } /> 50. Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations 51.
Render Will call getItems() which will display next items 52. GlassFish Application Server
53. Timeline of Project GlassFish Tomcat Jasper Catalina JSTL Struts Crimson XSLTC Xalan Xerces JAXB JAX-RPC JSF June 2005 May 2006 GlassFish Launch v2 v1 v3 Mid-2009 UR1 v2.1 UR2 v3 Prelude Oct 2008 Dec 2008 Sept. 2007 54. Demo Demo Netbeans 6.5 JPA entity JSF pages generation from DB tables 55. Agenda
56. Spring Framework Goals
57. Spring Framework 58. What Is Spring Not?
59. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components SpringBean Entity Class Catalog Item ItemController Spring Framework 60. Bean Factory and Dependency Injection Spring Bean Factoryinjects dependencies Application's POJOs Configuration file Dependencies inapplicationContext.xml Fully configured and ready to use objects 61. Spring Dependency Injection
Inject Spring Bean
applicationContext.xml 62. Spring 2.5 Dependency Injection
Inject Spring Bean
applicationContext.xml 63. Spring 2.5 Stereotypes and Autowiring
applicationContext.xml 64. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components SpringBean Entity Class Catalog Item ItemController Spring Framework 65. ItemController Bean and Spring Dependency Injection
Inject Spring Bean
66. Spring JSF Configuration infaces-config.xml
applicationContext.xml Will scan for components, don't have toconfiguremanaged beans infaces-config.xml org.springframework.web.jsf.el.SpringBeanFacesELResolver 67. Spring JSF Configuration inweb.xml
contextConfigLocation/WEB-INF/ applicationContext.xml org.springframework.web.context.ContextLoaderListener org.springframework.web.context.request.RequestContextListener 68. Rest of JSF stays the same
69. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components SpringBean Entity Class Catalog Item ItemController Spring Framework 70. Catalog Spring Bean Using JPA @Repository @Transactional public class CatalogDAO implementsCatalogService{ @PersistenceContext (unitName="PetCatalogPu") privateEntityManager em; @Transactional(readOnly=true) public ListgetItems (int firstItem,int batchSize) {Query q =em. createQuery("select object(o) from Item as o"); q.setMaxResults(batchSize); q.setFirstResult(firstItem); List items= q.getResultList(); return items;} Component Stereotype Spring transactions use aop 71. Configuration of catalogService Spring Bean in aplicationContext.xml
Scan for components 72. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components SpringBean Entity Class Catalog Item ItemController Spring Framework 73. JPA Entity stays the same @Entity public class Item implements Serializable { @Idprotected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimalname){this.price=price;} } 74. Configuring Persistence Provider Container managed JPA Defined data source TopLink Classfile enhancer, for lazy loading 75. Spring JPA Configuration forDerby JDBC driver 76. Spring & GlassFish Application Server
77. Get Spring (and this sample) from theGlassFish Update Center 78. Or Get Spring from from Netbeans Plugins catalog 79. Summary
80. Agenda
81. What is Seam?
82. WebBeansJSR 299
Component: Managed class can be injectedGavin KingJSR 299 lead, Sun,Google , Oracle... members Component: Definition of Managed class when name is requested, instantiated Scope: Context Buckets where the component instances are stored 83. Bean Validation FrameworkJSR 303
Emmanuel Bernard (Red Hat) JSR 303 lead, Sun, Google, Oracle... members 84. Seam Catalog ApplicationDB Session EJB EntitySeam Framework JSF Components CatalogBean Item 85. Seam Key Concepts
@Name = gives a name to reference a component Context ~=bucket 86. Seam Key Concepts
Context=bucket Scope=how long stored in context bucket @Name = gives a name to reference a component 87. Seam Key Concepts
88. Seam Catalog ApplicationDB Session EJB EntitySeam Framework JSF Components CatalogBean Item 89. JPA Entity & Seam @Entity @Name(" item ") @Scope(ScopeType.EVENT) public classItemimplements Serializable { @Idprotected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimalname){this.price=price;} } The@Nameannotation binds the component to a contextual variable its just likein the JSF XML 90. Seam Catalog ApplicationDB Session EJB EntitySeam Framework JSF Components CatalogBean Item 91. Seam JSF Configuration infaces-config.xml org.jboss.seam.jsf.SeamELResolver org.jboss.seam.jsf.SeamPhaseListener 92. Component Bindings List.jsp ... ... A snippet fromList.jsp 93. UIComponents Bindingto a Session EJB
Session Bean @DataModel for exposing to page @Factory for initializing Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page 94. Catalog Session EJB @Stateful @Scope(SESSION) @Name(" catalog ") @Interceptors ({org.jboss.seam.ejb. SeamInterceptor .class}) public classCatalogBeanimplements Serializable,Catalog{@PersistenceContext(unitName=PetCatalogPu)EntityManager entityManager; @DataModel private List items=null; @Factory(" items ") public voidgetItems(){ Query q = em.createQuery( "select object(o) from Item as o"); q.setMaxResults( batchSize ); q.setFirstResult( firstItem ); items= q.getResultList(); } Seam JSFDataModelcomponent SeamFactoryMethod, called on initialization 95. EJB 3.0Interceptors
interceptor
@Stateless public class CatalogBean { public void book() {} } 96. Component Bindings List.jsp ... ... A snippet fromList.jsp Action link@DataModelSelectionholds the selected value 97. UIComponents Bindingto a Session Bean
Session Bean JSF positions DataModel.getRowData() torow of actionbefore calling action listener
Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page 98. Invoke Application Phase
@Stateful @Scope(SESSION) @Name(" catalog ") @Interceptors ({... SeamInterceptor .class}) public classCatalogBeanimplements Serializable,Catalog @DataModel private List< Item > items =null; @DataModelSelection @Out(required=false) private Item item; public Stringselect(){ return"item_detail"; } Action methodNavigation response outject to theitemcontextvariable inject the DataModel rowitemcorresponding to clicked Link Action method 99. Navigation (same as before)from-view to-view from-outcome Navigation rulesin faces-config.xml,Or in Seam'spages.xml .list.jsp new_usr.jsp error.jsp error.jsp detail.jsp item_detail new user error 100. Seam Catalog ApplicationDB Session EJB EntitySeam Framework JSF Components CatalogBean Item 101. Standard request processing lifecycle Render Response Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations outjected itemevent context variable, available to JSP 102. Component Bindings Detail.jsp ... ... A snippet fromDetail.jsp @Out exposesvalue to page outjected itemevent context variable, available to JSP 103. Seam & GlassFish Application Server
104. Agenda
105. Summary
106. Which one,don't ask me
107. For More Information
108.
Carol McDonald Java Architect Tech Days 2009