Table of Contents EJB 3.1 and JPA 2

Size: px
Start display at page:

Download "Table of Contents EJB 3.1 and JPA 2"

Transcription

1 Table of Contents EJB 3.1 and JPA 2 Enterprise JavaBeans and the Java Persistence API 1 Workshop Overview 2 Workshop Objectives 3 Workshop Agenda 4 Course Prerequisites 5 Labs 6 Session 1: Introduction 7 Lesson Objectives 8 Overview 9 What is EJB 10 EJB Goals 11 EJB Goals (continued) 12 Types of Enterprise JavaBeans 13 Java Persistence API 14 EJB and Java EE (Enterprise Edition) 15 EJB in Java EE Architecture 16 SOA and EJB 17 SOA with Web Services and EJB 18 EJB 3 19 EJB 3 Overview 20 EJB 2.x Problems 21 EJB 3.0 Goals 22 EJB 3.1 Goals 24 Session Bean Usage 25 Session Bean Usage 26 Persistent Entity Usage 27 MDB Usage 28 Lab 1.1 Setting Up the Environment 29 Review Questions 30 Lesson Summary 31 Session 2: Session Beans 33 Lesson Objectives 34 Session Bean Overview 35 What are Session Beans 36 Stateless Session Beans (SLSB) 37 Stateful Session Beans (SFSB) 38 Session Beans Can Be Distributed 39 Defining a Session Bean 40 Stateless Session Bean Definition 41 Calculator Remote Business Interface 42 Remote and Local Business Interfaces 43 Calculator Bean Local Business Interface 44 A Brief Note on Annotations 45 How Annotations Work 46 Annotation Definition 47 Using Annotations 48 What Else Is Needed 49 Packaging and Deployment 50 Copyright LearningPatterns Inc. All rights reserved i

2 JEE Packaging 51 ejb-jar File 52 Deployment Descriptor (DD) 53 Deployment Descriptors in EJB 3 54 ejb-jar File Structure 55 Enterprise Archive (ear file) 56 Application.xml File 57 Web Application Structure - JEE 6 58 Server Deployment 59 EJB Container 60 The EJB Container 61 Server Deployment 62 Lab 2.1 Write and Deploy an EJB 63 JNDI Overview 64 How do Remote Clients Get EJB Access 65 JNDI Java Naming and Directory Interface 66 EJB Container Binds a Reference Into JNDI 67 Client Looks Up Reference In JNDI 68 JNDI Tree Structure 69 JNDI Tree Structure 70 JNDI API Overview 71 JNDI API 72 The Context Interface 73 The InitialContext Class 74 Specifying the InitialContext Properties 75 Using JNDI 76 EJB Remote Client 77 Client View of a Session Bean 78 EJB Portable JNDI Names 79 Portable JNDI Name Example 80 Client Invocation of a Session EJB 81 Running a Client 82 Lab 2.2 Write and Run an EJB Client 83 Review Questions 84 Lesson Summary 85 Session 3: Additional EJB Capabilities 87 Lesson Objectives 88 Dependency Injection 89 Dependency Injection 90 The JavaTunes Online Music Store 91 An EJB Referencing Another EJB 92 CatalogMaintenance 93 Injection of CatalogMaintenance 94 What is Happening 95 Lab 3.1 Dependency Injection 96 Deployment Descriptors 97 More about Deployment Descriptors 98 The XML Deployment Descriptor 99 Sample Standard Deployment Descriptor 100 The EJB Environment 101 Issues With Obtaining Resources 102 More Information on EJB References 103 Copyright LearningPatterns Inc. All rights reserved ii

3 Referencing Resources External to EAR 104 References & Deployment Descriptor Usage 105 Resolving a JNDI Name 106 Resolving a JNDI Name 107 Simple Environment Entries 108 Simple Environment Entry Example 109 Declaring Simple Environment Entries 110 Setter Injection 111 Resource Manager Connection Factories 112 Resource Manager Connection Factories 113 DataSource Reference Example - Bean 114 DataSource Reference Example - DD 115 More on the Enterprise Bean Environment 116 The Environment is a Level of Indirection 117 Looking Up Resources in the Environment 118 Looking up Via EJBContext 119 Looking up via JNDI API 120 More on Annotation Example 122 More on Annotation 123 More on Annotation 124 Deployment Descriptor vs Annotation 125 Lab 3.2 Simple Environment Entry 126 Stateless Session Bean Lifecycle & Interceptors 127 Overview 128 Stateless Session Bean State Diagram 129 Life Cycle of SSB 130 Client Call of a Stateless SB Method 131 Interceptors 132 Business Method Interceptors 133 Business Method Interceptors Example 134 InvocationContext Interface Details 135 Interceptor Method Details 136 Interceptor Class 137 Using Interceptor Classes 138 Method Level Interceptors 139 Lifecycle Callback Interceptors 140 Lifecycle Interceptor in the Bean Class 141 Lifecycle Interceptor in a Separate Class 142 Lab 3.3 Interceptors 143 Asynchronous Methods, Singleton Session Beans 144 Overview 145 Singleton Session Bean 146 Singleton Initialization 147 Singleton Concurrency 148 Asynchronous Method Invocations 149 Using Future 150 Stateful Session Beans 151 Stateful Session Bean (SFSB) Overview 152 Coding a Stateful Session Bean 153 Stateful Session Bean Removal 154 Stateful Session Bean Clients 155 Servlet Use of Stateful Session Beans 156 Servlet Use of Stateful Session Beans 157 Copyright LearningPatterns Inc. All rights reserved iii

4 Stateful Session Passivation/Activation 158 When to Use Stateful Session Beans Callbacks 160 Stateful Session Bean State Diagram 161 Lab 3.4 Stateful Session Beans 162 The Timer Service 163 Overview 164 Programmatic Timers 165 The javax.ejb.timer Interface 166 The javax.ejb.timerservice Interface 167 TimerService Methods (contd.) 168 Timer Example 169 How the Timer Works 170 ScheduleExpression: Calendar-Based Timers 171 ScheduleExpression Example 172 Issues with Programmatic Timers 173 Automatic Timers - javax.ejb.schedule Details 175 Lab 3.5 Timers 176 Review Questions 177 Lesson Summary 178 Session 4: Message-Driven Beans 181 Lesson Objectives 182 Overview of Messaging Systems 183 What is Messaging? 184 Loose Coupling 185 When is Messaging Used? 186 Two Messaging Models 187 Publish/Subscribe - Illustrated 188 More on Publish/Subscribe 189 Point-to-Point - Illustrated 190 More on Point-to-Point (P2P) 191 Message Delivery - Push versus Pull 192 Overview of JMS API 193 What is Java Message Service? 194 API Structure 195 JMS Interfaces 196 Administered Objects 197 Administered Objects and JNDI - Illustrated 198 Client Workflow 199 Queue Producer Client Example 200 Queue Producer Client Example 201 Synchronous Queue Consumer Client 202 Asynchronous Queue Consumer Client 203 Message Listener Example 204 JMS Message Types 205 Message Header Fields 206 Message-Driven Beans 207 JEE Message Producers and Consumers 208 Message-Driven Bean (MDB) Overview 209 Goals of Message-Driven Beans 210 Simple MDB Example 211 MDB Consumption of a Message 212 Copyright LearningPatterns Inc. All rights reserved iv

5 @MessageDriven Details 213 Activation Configuration Properties 214 Specifying a Destination for an MDB 215 Specifying a Destination Using a DD 216 Message-Driven Bean Lifecycle 217 Lifecycle Overview 218 MDB State Diagram 219 Interceptor Methods 220 Lab 4.1 Message Driven Bean 221 Review Questions 222 Lesson Summary 223 Session 5: Transactions and Security 224 Lesson Objectives 225 Transaction Definition 226 Transaction Overview 227 Transaction Lifecycle 228 Transactions Clarify Systems 229 Transactional System Overview 230 Overview of a Transactional System 231 Transactional System Components 232 Transactional System Components 233 Transactional Object 234 EJB Transaction Support 235 Transactions in EJB 236 EJB Declarative Transaction Management 237 Transactional Scope 238 EJB Transaction Attributes 239 Specifying Transaction Attributes 240 Specifying Transaction Attributes 241 NOTSUPPORTED 242 SUPPORTS 243 REQUIRED 244 REQUIRESNEW 245 MANDATORY 246 NEVER 247 Beans Have a Say in Transactions 248 Beans Can be Notified of Transaction Status 249 Transaction Example 250 Transaction Attributes Some Choices 251 Transaction Attributes - Some Choices 252 Explicit / Bean-Managed Transactions 253 UserTransaction & Bean-Managed Example 254 Transaction Isolation Levels 255 Transaction Isolation Levels Usage 256 Multi-process TX and Two Phase Commit 257 Lab 5.1 Transactions 258 Security in EJB 259 Security Requirements 260 JEE security 261 Roles 262 JEE Security Overview 263 EJB Security Overview 264 Copyright LearningPatterns Inc. All rights reserved v

6 Annotation Example 265 Example: Roles and Method Permissions 266 Annotation Example 267 Same Example With Annotations 268 Authentication 269 Programmatic Security 270 Example of Programmatic Security 271 Transport Level Security with SSL 272 Lab 5.2 Security 273 Review Questions 274 Lesson Summary 275 Lesson Summary 276 Session 6: Exception Handling and Best Practices 277 Lesson Objectives 278 Exception Handling 279 Overview of Exceptions 280 Exception Hierarchy 281 Application Exceptions in EJB 282 Defining Application Exceptions 283 Application Exception Example 284 Container Handling of Application Exception 285 Bean Throwing of Application Exception 286 Client Handling of Application Exceptions 287 System Exceptions Indicate Failure 288 Container Handling of System Exception 289 Client Handling of System Exceptions 290 EJB 3 Best Practices 291 When To Use EJB 292 Keep Business Interfaces Coarse Grained 293 Session Façade Structure 294 Use Container-Managed Transactions 295 Transaction Duration 296 Local and Remote Business Interface 297 Tuning 298 Session Bean Tuning 299 Clustering 300 Clustering Session Beans 301 Review Questions 302 Lesson Summary 303 Session 7: Introduction to the Java Persistence API (JPA 2) 305 Lesson Objectives 306 JPA Overview 307 The Issues with Persistence Layers 308 Object-Relational Mapping (ORM) Issues 309 Java Persistence API Overview 310 JPA Benefits 311 Java Persistence Environments 312 JPA Architecture High Level View 313 JPA Architecture Programming View 314 Mapping a Simple Class 315 Entity Classes 316 Entity Class Requirements 317 Copyright LearningPatterns Inc. All rights reserved vi

7 An Example Entity Class 318 javax.persistence.entity Annotation 319 The Event Class 320 javax.persistence.id and ID property 321 Field Access or Property Access 322 The EVENTS Table 323 Generated Id Property 324 Mapping Properties 325 Basic Mapping Types 326 Temporal (Date/Time) Mappings 327 Persisting to the Database 328 Lab 7.1 Mapping an Entity Class 329 Entity Manager and Persistence Context 330 The Persistence Unit 331 persistence.xml 332 Classes included in a persistence unit 333 The EntityManager & Persistence Context 334 EntityManager Interface 335 Obtaining an Entity Manager 336 Injecting an EntityManager 337 Container-Managed Entity Manger 338 Retrieving Persistent Objects 339 Lab 7.2 Using an Entity Class 340 More About Mappings 341 Default Mappings 343 Field and Property Access 344 Mapping Enums 345 Review Questions 346 Lesson Summary 347 Session 8: Updates and Queries 349 Lesson Objectives 350 Inserting and Updating 351 Persisting a New Entity 352 Persisting a New Entity Example 353 Synchronization To the Database 354 Updating a Persistent Instance 355 Removing an Instance 356 Detached Entities 357 Lab 8.1 Inserting and Updating 358 Querying and Java Persistence Query Language (JPQL) 359 Java Persistence Query Language 360 JPQL Basics SELECT Statement 361 Querying and the Query Interface 362 Executing a Query 363 JPA 2 Generic Query Enhancements 364 JPA 2 Generic Query Enhancements 365 Other Query Methods 366 Where Clause 367 JPQL Operators and Expressions 368 Query Parameters 369 Using Query Parameters 370 Named Queries 371 Copyright LearningPatterns Inc. All rights reserved vii

8 Named Queries 372 Lab 8.2 Basic Querying 373 Criteria API (JPA 2) 374 Criteria Overview 375 A Simple Criteria Example (1 of 3) 376 Path Expressions 379 WHERE Clauses 380 Typed Path Expressions 381 Typed Path Expressions 382 Combining Predicates (and/or) 383 Additional Criteria API Capabilities 384 [Optional] Lab 8.3 Criteria Query 385 The Persistence Lifecycle 386 The Persistence Lifecycle 387 JPA Entity States 388 Transient and Persistent State 389 Detached and Removed State 390 JPA Object States and Transitions 391 The Persistence Context 392 Persistence Context Lifespan 393 Persistence Context Propagation 394 The Persistence Context as Cache 395 Persistence Context and Object Identity 396 Synchronization To the Database 397 Flushing the Entity Manager 398 Yes, It's Complicated 399 Versioning / Optimistic Locking 400 Optimistic Locking 401 Using a Detached Instance 402 Using a Detached Instance Example 403 Using a Detached Instance Example 404 Versioning 405 Version Property in Java Class 406 Optimistic Locking Example 407 Locking Objects 408 [Optional] Lab 8.4 Versioning 409 Review Questions 410 Lesson Summary 411 Session 9: Entity Relationships 413 Lesson Objectives 414 Relationships Overview 415 Object Relationships 416 Characteristics of Relationships 417 Directionality 418 Directionality 419 Characteristics of Relationships 420 Mapping Relationships 421 Mappings Overview 422 Unidirectional Many-To-One Relationship 423 The Table Structure Many-To-One 424 The Owning Side 426 Copyright LearningPatterns Inc. All rights reserved viii

9 Using the Relationship 427 Bidirectional One-To-Many Relationship 428 Mapping the One-To-Many Relationship 429 Managing the Bidirectional Relationship 430 More on the Inverse Side 431 More on the Collection Declaration 432 Other Collection Types 433 Cascading Operations 434 Transitive Persistence 435 The cascade element 436 Lab 9.1 Relationships 437 Bidirectional One-To-One Relationship 438 Bidirectional One-To-One Relationship 439 Orphan Removal (JPA 2) 440 Many-To-Many Relationship 441 Defining Many-To-Many Relationship 442 Mapping Many-To-Many Relationships 443 Specifying the Join Table 444 Choosing Cascade Behavior 445 Lazy and Eager Loading 446 Queries Across Relationships 447 OUTER and FETCH JOIN 448 FETCH JOIN Example 449 Joins using Criteria API 450 Lab 9.2 Working With Relationships 451 Mapping Inheritance 452 Entity Inheritance 453 Entity Inheritance 454 Details of Entity Inheritance 455 Single-Table Strategy 456 Entity Definitions for Single-Table 457 Sample Table Entries 458 Single-Table: Pros and Cons 459 Joined (Table per Subclass) 460 Entity Definitions for Joined 461 Joined: Pros and Cons 462 Table per Concrete Class 463 Lab 9.3 Working With Inheritance 464 Embedded Objects 465 Using Embedded Objects 466 Embeddable Class 467 Reusing Embeddable Classes 468 Overriding Embedded Class Attributes 469 Compound Primary Keys 470 Compound Primary Keys 471 Compound Key With Embedded Id Class 472 Using an Embedded Id Class 473 Compound Key With Id Class 474 Compound Key With Id Class 475 Element Collections (JPA 2) 476 Element Collections 477 Modeling a Collection of String Elements 478 Mapping an Element Collection (Basic Type) 479 Copyright LearningPatterns Inc. All rights reserved ix

10 Using an Element Collection 480 Collections of Embeddable Components 481 Mapping Collections of Embeddables 482 Review Questions 483 Review Questions 484 Lesson Summary 485 Session 10: [Optional] Additional Java Persistence Capabilities 489 Lesson Objectives 490 More on Querying 491 Projection Queries 492 Aggregate Queries 493 Aggregate Query Examples 494 Bulk Update and Delete 495 Native SQL Queries 496 Extended Persistence Contexts 497 Stateful Session Beans with Entity State 498 Extended Persistence Context 499 Issues with Extended Persistence Context 500 XML Mapping Files 501 XML Mapping Files 502 A Simple Entity Class 503 JPA XML Mapping File 504 JPA XML Mapping File - Mapping Entities 505 JPA XML Mapping File - Named Queries 506 Java Persistence with Java SE 507 Using JPA with Java SE 508 Java SE APIs 509 Example of JPA in Java SE 510 Java Persistence Best Practices 511 Primary Key Considerations 512 Use Named Queries 513 Use Lazy/Eager Loading Appropriately 514 Be Aware of Transaction Semantics 515 Encapsulate JPA Code 516 Use Report Queries Where Applicable 517 Optimize Read-Only/Mostly Data Access 518 Paging Data 519 Consider Going Outside of Java Persistence 520 Know Your Provider Implementation 521 Resources (EJB3 and JPA) 522 Resources 523 Copyright LearningPatterns Inc. All rights reserved x

11 Enterprise JavaBeans and the Java Persistence API The Java Developer Education Series Java, EJB, Enterprise JavaBeans and all Java-based trademarks are registered trademarks of Oracle, Inc Copyright LearningPatterns Inc. All rights reserved. 1

12 Preface Workshop Overview This course provides a thorough introduction to Enterprise JavaBeans V3.1, including The needs EJB is designed to address The basic concepts and architecture Thorough coverage of the EJB API and details on its use Thorough coverage of the Java Persistence API V2 (JPA 2) Design principles for correct usage The workshop consists of at least 50% hands-on lab exercises, including a series of labs designed to exercise all important concepts Most of the labs follow a common fictional case study - JavaTunes, an online music store CDs (Item table), Inventory (Inventory table) and others Copyright LearningPatterns Inc. All rights reserved. 2

13 Preface Workshop Objectives At completion you should be able to Understand how EJB relates to the rest of Java/Java EE Understand EJB concepts and architecture Be familiar with the EJB API, including the Java Persistence API (JPA) Be able to write and use EJBs Be familiar with the JPA API, and be able to write and use persistent entities, including advanced capabilities like relationships and inheritance Understand the tradeoffs involving EJB Understand important design principles for EJB Copyright LearningPatterns Inc. All rights reserved. 3

14 Preface Workshop Agenda Session 1: Introduction to EJB Session 2: Session Bean Architecture and API Session 3: Additional EJB Capabilities Session 4: Message-Driven Bean Architecture and API Session 5:Transactions and Security Session 6: Exceptions and Best Practices Session 7: Java Persistence API 2 (Entity Beans) Intro Session 8: Java Persistence API Inserts and Queries Session 9: Java Persistence API Associations Session 10: Java Persistence API Additional Capabilities Copyright LearningPatterns Inc. All rights reserved. 4

15 Preface Course Prerequisites Proficiency in Java and Object-Oriented programming General knowledge of Java EE (Enterprise Edition) Knowledge of relational databases Copyright LearningPatterns Inc. All rights reserved. 5

16 Preface Labs Lab The workshop has numerous hands-on lab exercises, structured as a series of brief labs Many follow a common fictional case study called JavaTunes An online music store There is a placeholder slide for each lab in the manual The detailed lab instructions are at the end of the manual Setup zip files are provided with skeleton code for the labs Students add code focused on the topic they're working with There is a solution zip with completed lab code The end of a lab is marked with a stop like this one: STOP Copyright LearningPatterns Inc. All rights reserved. 6

17 Session 1: Introduction Session 1: Introduction Overview EJB 3.1 Copyright LearningPatterns Inc. All rights reserved. 7

18 Session 1: Introduction Lesson Objectives Gain a high level understanding of EJB and EJB architecture Understand how EJB fits into the Java EE architecture Understand how EJB relates to other technologies Become acquainted with EJB 3.1, its goals, and the problems with earlier versions Copyright LearningPatterns Inc. All rights reserved. 8

19 Session 1: Introduction Overview Overview EJB 3.1 Copyright LearningPatterns Inc. All rights reserved. 9

20 Session 1: Introduction What is EJB EJB is a framework for creating server-side components that are: Transactional, Distributed, Portable, Reliable, Secure, Scalable It simplifies the building of multi-tier distributed object applications EJB is a technology to create business-tier components for these kinds of applications EJB provides a server-side framework for providing a core set of system services to Java components Services such as low-level transaction and state management, multi-threading, and connection pooling Copyright LearningPatterns Inc. All rights reserved. 10

21 Session 1: Introduction EJB Goals Provide a standard distributed component architecture for Java applications Allowing easy creation of distributed business applications Portable across many vendors (write once, run anywhere) Fitting into the Java EE (Enterprise Edition) architecture Enabling the use of third-party development tools Generally meant for creating business tier components Relieve developers from managing transactions, threads, security, resource management, while still providing access to low-level APIs These kinds of issues are generally taken care of by the EJB framework Copyright LearningPatterns Inc. All rights reserved. 11

22 Session 1: Introduction EJB Goals (continued) Provide a persistence framework to simplify Object-Relational Mapping (ORM) The issue of mapping a set of (Java) objects to information in a relational database is complex The data is in different forms Going from one form to the other is difficult, and writing the code is tedious Persistent entities provide a framework to automate the mapping of Java objects to relational data A mapping is defined via metadata, and the framework generates the JDBC code to work with the data Copyright LearningPatterns Inc. All rights reserved. 12

23 Session 1: Introduction Types of Enterprise JavaBeans Session Beans provide a business service Distributed, transactional Bean instances live in a software environment called the EJB container The container manages the lifecycle of instances, as well as distributed access, transactions, etc. Message Driven Beans (MDB) integrate EJB with messaging (JMS) systems An MDB is an asynchronous message consumer It consumes messages from a queue or topic Makes asynchronous processing of incoming messages on the server simpler Allows for concurrent processing of a stream of messages by means of container managed pooling Copyright LearningPatterns Inc. All rights reserved. 13

24 Session 1: Introduction Java Persistence API The brand new Java Persistence API defines a Java persistence framework Persistent Entities provide Object-Relational Mapping (ORM) capabilities Persistent entities are lightweight persistent domain objects Primary concern is mapping objects to relational data Persistent entities are not distributed objects, though they may be accessed in a distributed way using a session bean façade Persistent entities are not really "Entity Beans" They are a separate part of the specification now Can be used separately from other parts of EJB In a new package, javax.persistence, not in javax.ejb The Java Persistence API is a separate part of the same specification defining EJB (JSR-220) It is required for all EJB containers However, it can also be used separately if only Java Persistence is needed Copyright LearningPatterns Inc. All rights reserved. 14

25 Session 1: Introduction EJB and Java EE (Enterprise Edition) Java EE is an architecture for building multi-tier enterprise applications Umbrella for many other Java technologies including: EJB, Servlets/JSP, JMS, RMI EJB serves as the distributed component technology and persistence framework for Java EE Generally, EJB is used on the server side It is often invoked from the Web tier, but may be invoked by thick clients (e.g. Swing clients) It can also be used in Service Oriented Architectures (SOA) Java EE was previously known as J2EE With the release of Java 5 / Java EE 5, the 2 was dropped from the names Copyright LearningPatterns Inc. All rights reserved. 15

26 Session 1: Introduction EJB in Java EE Architecture Web clients communicate via HTTP Rich clients can communicate via HTTP or RMI presentation business persistence client application server DB server browser HTTP client HTTP servlets JSPs Session EJB Persistent Entity database Swing GUI RMI This architecture may be attractive because you can support both Web browser clients and Swing clients, and do so in several different ways. Web browser clients interact with the EJB business tier indirectly, via the servlet/jsp presentation tier. Swing clients can generate HTTP requests to the servlet/jsp presentation tier or can interact directly with the EJB business tier. You might want to do this to reuse an existing servlet/jsp interface or to use HTTP to get through a firewall. We will talk about MDB later Copyright LearningPatterns Inc. All rights reserved. 16

27 Session 1: Introduction SOA and EJB SOA (Service Oriented Architecture) is an important basis for enterprise architectures Based on providing resources on a network As independent services independent of their implementation Results in loosely coupled architecture EJB can support SOA in multiple ways The services can be exposed directly as a session EJB SOA is usually thought of in terms of Web Services (e.g. SOAP), but EJB may be a useful alternative in some cases This usually requires Java clients A Web Service can be implemented using EJB Web Services are just a façade for exposing a service The service has to be implemented in some way either as an EJB or as a regular Java object Choosing to use EJB in a service oriented architecture is entirely valid Web Services add a layer of complexity and inefficiency If you don't need the advantages of Web Services, then don't use them In fact, you can even invoke EJB from non-java clients This uses CORBA It's not really a practical architecture unless you're already using a CORBA architecture Copyright LearningPatterns Inc. All rights reserved. 17

28 Session 1: Introduction SOA with Web Services and EJB Another popular Java EE architecture Provides loosely coupled access via standard protocols Web services business Java Client application server Web Services.NET Client SOAP/ HTTP SOAP/ HTTP Web Services Servlet EJB Web Services In this type of architecture, SOAP/HTTP is used as the communication protocol, and the service is implemented using EJB Servlets are used purely to support SOAP over HTTP, and are not really involved in presentation layer aspects Copyright LearningPatterns Inc. All rights reserved. 18

29 Session 1: Introduction EJB 3 Overview EJB 3 Copyright LearningPatterns Inc. All rights reserved. 19

30 Session 1: Introduction EJB 3 Overview Complete reworking of EJB specification Major differences from EJB 2.x Some areas have changed completely Uses Java annotations heavily Reduces the use of XML configuration files (Deployment Descriptor), and can eliminate them Persistence is completely different from earlier releases Total overhaul of EJB persistence Persistent entities much lighter weight Based on mature ORM technologies such as Hibernate & Toplink Persistent entities can't be invoked remotely Persistence can be used separately from other parts of EJB Copyright LearningPatterns Inc. All rights reserved. 20

31 Session 1: Introduction EJB 2.x Problems Cumbersome and difficult to program Each EJB required (at a minimum) an implementation class, a home interface, a remote interface, and a deployment descriptor The API was invasive all the interfaces and classes were directly tied to EJB specific types (via inheritance, implementing an interface, etc.) Client programs were also exposed to some of this complexity Entity beans were not very useable Some would say they were broken The specification was also incomplete in terms of what was required in terms of ORM, and how it was to be done They were not used very much Copyright LearningPatterns Inc. All rights reserved. 21

32 Session 1: Introduction EJB 3.0 Goals Simplify development Annotations make programming simpler Fewer classes required API is simpler Use POJOs and POJIs Bean implementations can be POJO (Plain Old Java Objects) Remote interfaces can be POJI (Plain Old Java Interfaces) These are much easier to program Reduces coupling to EJB specific types Interceptor capability for session and message-driven beans Remove need for home interfaces Copyright LearningPatterns Inc. All rights reserved. 22

33 Session 1: Introduction EJB 3.0 Goals Make the most common usage easy Defaults for most things, to reduce need for developer to specify common, expected behaviors e.g. no empty ejbactivate() methods as in EJB 2.x Resource and environmental dependencies easier Dependency injection, annotations simplify programming Support entity persistence well Simpler API Much more powerful capabilities, including support for inheritance, polymorphism, relationships, embedded components No required interfaces used - entities are POJOs Copyright LearningPatterns Inc. All rights reserved. 23

34 Session 1: Introduction EJB 3.1 Goals Improve usability and functionality of EJB 3.0, including: EJB without business interface (for local view) Define portable global JNDI names for lookup Add singleton session bean capability Easy-to-use calendar-based timer service Simple asynchronous session beans EJB packaging within WAR files EJB lite - subset of complete EJB capability Copyright LearningPatterns Inc. All rights reserved. 24

35 Session 1: Introduction Session Bean Usage Session beans provide a number of useful capabilities Transaction Management Session beans provide easy access to the transaction service available in EJB Transactional behavior can be easily specified with annotations in the bean class Resource Management / Concurrent Access EJB container manages bean instances, threads, memory issues Very important for scalability in enterprise applications Distributed Services / SOA Session beans can be accessed remotely (directly via RMI) Can also be used to implement Web Services Copyright LearningPatterns Inc. All rights reserved. 25

36 Session 1: Introduction Session Bean Usage Fault Tolerance / Scalability Most EJB containers support failover/high availability and some form of load balancing / clustering Security Beans and individual methods in beans can be tied into the JEE security system to secure access to them Can be done by setting security attributes (in bean class via annotations, or in XML DD) Copyright LearningPatterns Inc. All rights reserved. 26

37 Session 1: Introduction Persistent Entity Usage ORM Persistent entities are exclusively devoted to ORM They model business data, and handle the interaction with the database You define a mapping from the bean class to the database, and the framework generates all the JDBC code Eliminates the need for complex, tedious, hand coded JDBC Persistence available in Java SE - The persistence framework (javax.persistence) can be used independently Does not need Java EE server Can be used directly from Java SE (Standard Edition) program Copyright LearningPatterns Inc. All rights reserved. 27

38 Session 1: Introduction MDB Usage Integrate EJB/server with messaging Allows you to easily receive messages asynchronously on the server side Previous to MDB, there was no standard way to do this Transaction Management Allows you to easily start/control transactions when receiving JMS messages Can't be done directly for asynchronous message receipt with the JMS API Copyright LearningPatterns Inc. All rights reserved. 28

39 Lab 1.1: Setting up the Environment Lab 1.1 Setting Up the Environment In this lab you will become familiar with and set up your application server and development environment Copyright LearningPatterns Inc. All rights reserved. 29

40 Session 1: Introduction Review Questions What is EJB? What are the different kinds of beans defined in EJB, and what are they used for? How is EJB 3 better than previous versions of EJB? Copyright LearningPatterns Inc. All rights reserved. 30

41 Session 1: Introduction Lesson Summary EJB is a framework for creating server-side components Transactional, Distributed, Portable, Reliable, Secure, Scalable It also defines a persistence API EJB defines session beans, message-driven beans and persistent entities Session beans provide distributed business services, and access to container services such as transactions, concurrency control, etc. Message-driven beans receive JMS messages asynchronously, and integrate JMS with the EJB tier Persistent Entities provide an ORM framework to map between Java objects and relational data Copyright LearningPatterns Inc. All rights reserved. 31

42 Session 1: Introduction Lesson Summary EJB 3 simplifies and improves EJB in a number of ways Uses Java annotations to eliminate/reduce the need for XML deployment descriptors Developers work with POJOs and POJIs rather than having to derive from EJB specific interfaces and classes The persistence technology has been completely rewritten based on proven ORM technology The persistence technology has been separated from the rest of the specification and can be used independently EJB 3.1 added more usability features and functionality Singleton EJB, asynchronous EJB Packaging EJB in a WAR Portable JNDI names Copyright LearningPatterns Inc. All rights reserved. 32

43 Session 7: Introduction to the JPA Session 7: Introduction to the Java Persistence API (JPA 2) JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright LearningPatterns Inc. All rights reserved. 305

44 Session 7: Introduction to the JPA Lesson Objectives Describe the issues of object-relational mapping Describe the overall goals of the Java Persistence API Version 2 (JPA 2) Describe the JPA architecture Create a simple JPA application Map a simple class to a DB using JPA Copyright LearningPatterns Inc. All rights reserved. 306

45 Session 7: Introduction to the JPA JPA Overview JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright LearningPatterns Inc. All rights reserved. 307

46 Session 7: Introduction to the JPA The Issues with Persistence Layers Data - core element of many apps, often in relational DB Much effort expended on persistence layers to store /retrieve this data Complicated to write "Homegrown" solutions often buggy and incomplete DB schema changes often expensive to propagate to persistence layer OO languages (e.g. Java) complicate this more Simple JDBC access has many issues: Low level SQL - not object based To persist an object to the DB you write the SQL to do it To load an object from the DB, write SQL, and get result rows from the DB, which must usually be converted to objects hich must be converted into objects Copyright LearningPatterns Inc. All rights reserved. 308

47 Session 7: Introduction to the JPA Object-Relational Mapping (ORM) Issues When using an OO language with a relational database, you are working with different models of using data OO: Interacting objects traversed via relationships Relational: Tables that are joined via foreign key relationships These are very different models Translating from one to the other requires work There are many issues to deal with Example, Inheritance: A core feature of OO models Not supported in relational model Relational Associations: only foreign key relationships Object model: 1-1, 1-N, N-N Copyright LearningPatterns Inc. All rights reserved. 309

48 Session 7: Introduction to the JPA Java Persistence API Overview Completely new persistence framework for Java Totally different from previous frameworks Draws on technology from Hibernate, Toplink, JDO, and others Replaces EJB Entity Beans Overall goals Provide ORM capability for using a Java OO domain model to manage a relational database Provide a light-weight POJO based framework for Java persistence, including inheritance and polymorphism Provide a query language (an extension of EJB QL) that helps remove or encapsulate vendor specific SQL code Relieve the developer from 95% of common data persistence related programming tasks JPA replaces the Entity bean technology in previous releases of EJB Entity beans had significant problems in their architecture, and they never caught on There have been many ORM frameworks for Java available before JPA For example, Toplink, Hibernate, Kodo, and JDO JPA provides a standard set of capabilities and a standard API for working with ORM Copyright LearningPatterns Inc. All rights reserved. 310

49 Session 7: Introduction to the JPA JPA Benefits Simplicity and flexibility POJO based! ORM is completely metadata driven (annotations or XML) No need to write JDBC code Common defaults that allow metadata to be minimized Persistence API is totally separate from entity classes Can be used in Java SE environments (without app server) Completeness Supports full range of OO features Inheritance, custom object types, collections, associations Powerful query language Performance Minimizes number of database updates Lazy load on collections, disabling retrieval of associated objects Object caching JPA makes heavy use of defaults The amount of metadata is minimized as much as possible In some cases, almost no metadata will be needed Copyright LearningPatterns Inc. All rights reserved. 311

50 Session 7: Introduction to the JPA Java Persistence Environments Java Persistence introduced as standard part of JEE 5 JPA 2 part of JEE 6 Java Persistence can also be used in Java SE programs It is packaged as a set of jar files There are some minor configuration and programming differences from using it in a Java EE environment We'll show how to do it both ways Application server support is widespread Almost all application servers are supporting JPA Most JPA support is built on top of a few existing technologies e.g. Oracle/Sun Toplink based, Weblogic Kodo based, JBoss Hibernate based Copyright LearningPatterns Inc. All rights reserved. 312

51 Session 7: Introduction to the JPA JPA Architecture High Level View JPA uses database configuration data and entity metadata to provide persistence services and objects to the application Generally, the JPA implementation is built over an existing persistence provider, which in turn is built over JDBC Application Mapped Entity Classes JPA Persistence Provider (e.g. Hibernate or TopLink) JDBC Database Copyright LearningPatterns Inc. All rights reserved. 313

52 Session 7: Introduction to the JPA JPA Architecture Programming View There are a number of key types in using JPA Persistence: For configuration of the system EntityManager: Manages a set of persistent entities EntityManagerFactory: Factory for EntityManagers Query: For finding entities Entity: POJO class mapped using JPA Copyright LearningPatterns Inc. All rights reserved. 314

53 Session 7: Introduction to the JPA Mapping a Simple Class JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright LearningPatterns Inc. All rights reserved. 315

54 Session 7: Introduction to the JPA Entity Classes An entity is a lightweight persistent domain object Entities are fine-grained objects representing state stored in a DB An entity is one of the primary programming artifacts of JPA Entities Must be persistable i.e. have a database representation Have a persistent identity basically the primary key in the DB Are normally created/updated/deleted within a transaction Entity metadata describes the mapping to the data store Can be done with annotations (usually preferred) or XML The metadata required is minimized through the use of intelligent defaults The core annotations are in the package javax.persistence The concept of an entity has been present in database architecture for a long time An entity is basically a set of data that is grouped together It may participate in relationships to other entities In JPA any application defined object can be an entity Copyright LearningPatterns Inc. All rights reserved. 316

55 Session 7: Introduction to the JPA Entity Class Requirements Must be configured as an entity (via annotation or XML) Implement a no argument constructor for JPA to instantiate instances (may have other constructors) Contain instance variables to hold persistent state Must NOT be declared public Clients of the entity use accessor methods (get/set) for all persistent fields Provide an identifier property (usually called id) Maps to primary key in database Primitive type, or primitive wrapper, String, Date, composite key If instances will be passed as a detached object (e.g. through a remote interface), it must implement Serializable From the JPA 2 specification: The entity class must be annotated with the Entity annotation or denoted in the XML descriptor The no-arg constructor must be public or protected. The entity class must be a top-level class. An enum or interface must not be designated as an entity. The entity class must not be final. No methods or persistent instance variables may be final. If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface. Entities support inheritance, polymorphic associations, and polymorphic queries. Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes. The persistent state of an entity is represented by instance variables, which may correspond to Java-Beans properties. An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself. Instance variables must not be accessed by clients of the entity. The state of the entity is available to clients only through the entity s methods i.e., accessor methods (getter/setter methods) or other business methods. Copyright LearningPatterns Inc. All rights reserved. 317

56 Session 7: Introduction to the JPA An Example Entity Class package com.javatunes.schedule; import java.sql.date; import javax.persistence.entity; import public class Event implements java.io.serializable private Long id; private String title; private Date date; Event() {} public Event(Long id) { setid(id); } public Long getid() { return id; } private void setid(long id) { this.id = id; } public Date getdate() { return date; } public void setdate(date date) { this.date = date; } } public String gettitle() { return title; } public void settitle(string title) { this.title = title; } Regular classes can be transformed into entities by simply adding appropriate annotations The class needs a no-arg constructor You can also use an XML configuration file to declare that a class is an entity In general, annotations are much more widely used, and will be used in this class The persistent fields or properties of an entity may be of the following types: Java primitive types and wrappers of the primitive types java.lang.string; java.math.biginteger, java.math.bigdecimal java.util.date, java.util.calendar, java.sql.date, java.sql.time, java.sql.timestamp user-defined serializable types, byte[], Byte[], char[], and Character[]); enums; entity types and/or collections of entity types; embeddable classes Copyright LearningPatterns Inc. All rights reserved. 318

57 Session 7: Introduction to the JPA javax.persistence.entity declares the class to be a persistent entity The name of the entity defaults to the unqualified name of the class (Event) This name is used in queries, which we cover later The name can also be set with the name By default, it will be mapped to a table called Event You can to declare a different table name For example, if the table was called "EVENTS" you could use: public class Event { /*... */ has only one element name: The name of the entity for use in things like queries The default table name is the Entity name Which in our case is the default value of the unqualified name of the class It can be also has the following elements: catalog: The catalog of the table schema: The schema of the table uniqueconstraints: Unique constraints to be placed on the table (used only if the table is generated from the Entity class) These are all only useful if you are generating the DDL (table definitions) from the JPA entities It is in the javax.persistence package Copyright LearningPatterns Inc. All rights reserved. 319

58 Session 7: Introduction to the JPA The Event Class The event class has three properties id (Long), date (java.sql.date), title (String) The id property holds a unique identifier for each event Has JavaBean style get/set methods for all the properties Also has no-argument constructor By default, all non-transient properties are persistent That is, they are stored in the database By default, they are stored in a column with the same name as the property The column type in the database also uses reasonable defaults Non-persistent properties can be annotated Fields that use the Java transient modifier are also not persisted JPA tries to use defaults that minimize the amount of metadata (annotation) information that is required in your entity classes If a property is present in your class, it is persistent according to the standard, basic defaults An annotation may be placed on the property to document this, but it's not necessary Note that the setter for id is private in our class definition Programs will not be allowed to change this value This is a common way of defining the accessor methods for the id Copyright LearningPatterns Inc. All rights reserved. 320

59 Session 7: Introduction to the JPA javax.persistence.id and ID denotes that this property holds the primary key A class must have a primary key A non-composite primary key must correspond to a single field in an entity (e.g. the id field in the Event class) A simple primary key must be one of the following: Java primitive or wrapper class (integral types most common) java.lang.string, java.util.date, java.sql.date Generated primary keys are supported Only integral types will be portable Composite primary keys are also possible These use a primary key class A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties A primary key class must be defined to represent a composite primary key Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several are used to denote composite primary keys Copyright LearningPatterns Inc. All rights reserved. 321

60 Session 7: Introduction to the JPA Field Access or Property Access In the Event class, the persistence runtime will access the persistent fields directly in our event class This is because we have annotated the persistent fields It is also possible to annotate the accessor (getter/setter) methods (see below) In that case, the runtime will access the properties via the accessor methods This may be useful if you have business logic in the accessor methods (e.g. validation logic) You should not mix field and accessor styles within a class This is not // property access is used public Long getid() { return id; } Caution should be exercised in adding business logic to the accessor methods when property-based access is used. The order in which the persistence provider runtime calls these methods when loading or storing persistent state is not defined. Logic contained in such methods therefore cannot rely upon a specific invocation order. [JPA 2 Specification, Final, sec. 2.2] Copyright LearningPatterns Inc. All rights reserved. 322

61 Session 7: Introduction to the JPA The EVENTS Table Let's assume that the EVENTS table is declared as below Assume you are using a generated primary key A very common situation The SQL shown is for the open source Derby database using an Identity column We'll look at how to map our Event class based on this table CREATE TABLE EVENTS ( EVENT_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) EVENT_DATE DATE, TITLE VARCHAR(80), CONSTRAINT PK_EVENTS PRIMARY KEY(EVENT_ID) ); JPA has support for other types of generated values For example, sequences and table generated keys Copyright LearningPatterns Inc. All rights reserved. 323

62 Session 7: Introduction to the JPA Generated Id Property You to specify a generation strategy for primary keys Possible strategies are: AUTO: Persistence provider picks best strategy for DB IDENTITY: Uses DB identity column SEQUENCE: Uses DB sequence column TABLE: Uses underlying database table You to specify the column name Both annotations are @Column(name="EVENT_ID") private Long also allows you to define a generator for the has a large number of optional elements For example: nullable, nullable="false", unique=true) Some of these (e.g. nullable) are only used if you are generating the DDL from the entity declarations We'll cover some of them in the course See the documentation for complete coverage All these types are in the javax.persistence package The AUTO strategy only makes sense if the runtime is generating the table definitions Otherwise, of course, you'll need to use what's actually in the DB definition Copyright LearningPatterns Inc. All rights reserved. 324

63 Session 7: Introduction to the JPA Mapping Properties By default, all properties are considered persistent and mapped to columns with the same name as the property However, all the defaults may not be appropriate for us In our example, we map the date property to the EVENT_DATE column The title property will map to the TITLE column by default, so we don't need to do anything to change the defaults // package / imports not shown in most public class Event implements java.io.serializable @Column(name="EVENT_ID") private Long id; private String private Date date; // Other code omitted... Notice that we've used a java.sql.date in our class That's because we designed it to be used with JPA If you have a property that is a java.util.date, or a java.util.calendar, then JPA won't know how to map it Because it might be a date, a time, or a timestamp in the database For java.util.date and java.util.calendar must be used to specify how it is mapped to the database Here we specify it should be mapped as private java.util.date somedate; The other values of TemporalType are: TIME : Map as java.sql.date TIMESTAMP : Map as java.sql.timestamp Copyright LearningPatterns Inc. All rights reserved. 325

64 Session 7: Introduction to the JPA Basic Mapping Types JPA can map a large number of persistable types It automatically maps them to a JDBC type in the DB If the type in the DB is different, it will do its best to convert it The persistent fields or properties of an entity may be of the following types: Java primitive types and wrappers of the primitive types java.lang.string; java.math.biginteger, java.math.bigdecimal java.util.date, java.util.calendar, java.sql.date, java.sql.time, java.sql.timestamp byte[], Byte[], char[], and Character[]); Enums; User-defined serializable types, Entity types and/or collections of entity types; Embeddable classes The simple types above are mapped as part of the immediate state of the entity They include almost all information that you want to persist Sometimes the type in the database is not exactly the Java type In almost all cases, the provider runtime can convert between the two types If the provider can't do the conversion, then generally an exception will be thrown Copyright LearningPatterns Inc. All rights reserved. 326

65 Session 7: Introduction to the JPA Temporal (Date/Time) Mappings Temporal mappings can get somewhat complicated There are multiple Java and database types, and the default mappings between them are: java.sql.date: DATE java.sql.time: TIME java.sql.timestamp: is used to map java.util.date and Calendar to the appropriate SQL type, as shown at bottom These Java types are not specific enough for JPA to determine the DB type, must be used Can specify either DATE, TIME, or private Date date; java.util.date and java.util.calendar do not supply enough information for JPA to map to the database java.sql.date will map to a DATE column by default Our date property in MusicItem is of type java.util.date, so we will need to Copyright LearningPatterns Inc. All rights reserved. 327

66 Session 7: Introduction to the JPA Persisting to the Database An entity manager (abbreviated EM) is used to persist to the database It is represented by the javax.persistence.entitymanager interface This interface encapsulates the API for persisting to the database We'll look at this shortly The entity manager API is completely separate from the mapping definition of an entity class These responsibilities are not included in the mapping definition This allows for a much cleaner definition of an entity class Copyright LearningPatterns Inc. All rights reserved. 328

67 Lab 7.1 Mapping an Entity Class Lab 7.1 Mapping an Entity Class In this lab we will map our MusicItem class to the database: Copyright LearningPatterns Inc. All rights reserved. 329

68 Session 7: Introduction to the JPA Entity Manager and Persistence Context JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright LearningPatterns Inc. All rights reserved. 330

69 Session 7: Introduction to the JPA The Persistence Unit A persistence unit defines the set of entities that can be managed by an entity manager (covered next) A persistence unit defines the types that can be managed, the database they are persisted to, and the underlying mechanism used to persist entities (the persistence provider) A persistence unit is named and configured in a configuration file (usually called persistence.xml) It must be included in the META-INF directory of one of the jar files in the application (called the root of the persistence unit) It provides for standard JPA configuration Also allows provider specific configuration properties which are passed through to the underlying provider The persistence unit will be packaged up in a persistence archive Basically just a jar that contains persistence.xml in the META-INF directory The root jar file can be a regular jar, an ejb-jar, and others The persistence unit is basically a configuration artifact that lets you specify things like how the DB is accessed, global configuration information such as transaction manager type, etc. Copyright LearningPatterns Inc. All rights reserved. 331

70 Session 7: Introduction to the JPA persistence.xml persistence.xml, as in the example below, defines a persistence unit <persistence> specifies the namespaces and versions (JPA 2 ) <persistence-unit> defines the persistence unit The required name attribute specifies the persistent unit name The optional transaction-type attribute specifies transaction type <jta-data-source> specifies the datasource JNDI lookup name JTAl (i.e. container transactions) used here suitable for Java EE * <properties> let you to pass configuration properties to the provider <?xml version="1.0" encoding="utf-8"?> <persistence xmlns=" " version"2.0"> <!-- namespaces not shown --> <persistence-unit name="events" transaction-type="jta"> <jta-data-source>java:/eventds</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.derbydialect"/> </properties> </persistence-unit> </persistence> The root <persistence> element specifies the namespaces and version according to the JPA spec The labs and the example above are compatible with JPA 2 The labs include the complete namespace declarations which are not shown to save space Different environments will use different transaction types For example, in a Java SE environment, we would use JDBC transactions, and have transactiontype="resource_local" Different underlying providers will require different configuration mechanism The property capability shown allows you to pass whatever properties the provider needs These are dependent on the provider, and will vary for different providers The hibernate.dialect property is a vendor specific property used to configure an underlying Hibernate provider It specifies the type of database that is being used This allows Hibernate to optimize the SQL for that database There are a number of other elements available in persistence.xml See the documentation for more detail Copyright LearningPatterns Inc. All rights reserved. 332

71 Session 7: Introduction to the JPA Classes included in a persistence unit The classes included in a persistence unit are defined by: Annotated managed persistence classes contained in the root of the persistence unit (unless exclude-unlisted-classes is specified) One or more object/relational mapping XML files One or more jar files that will be searched for classes An explicit list of classes Generally, in a Java SE environment, you will use auto-scanning, where annotated persistent classes are automatically detected The code sample below shows how to list them explicitly, if desired (done in persistence.xml) <!-- Disable scanning --> <exclude-unlisted-classes>true</exclude-unlisted-classes> <!-- Include the Event class --> <class>com.javatunes.event</class> From the JPA spec [JPA 2 Specification, Final, Sec ] All classes contained in the root of the persistence unit are searched for annotated managed persistence classes classes with the Entity, Embeddable, or MappedSuperclass annotation and any mapping metadata annotations found on these classes will be processed, or they will be mapped using the mapping annotation defaults. If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element must be specified as true. The exclude-unlisted-classes element is not intended for use in Java SE environments. A object/relational mapping XML file named orm.xml [with mapping information for the classes listed in it] may be specified in the META-INF directory in the root of the persistence unit or in the META-INF directory of any jar file referenced by the persistence.xml. Alternatively, or in addition, one or more mapping files may be referenced by the mapping-file elements of the persistence-unit element. These mapping files may be present anywhere on the class path. An orm.xml mapping file or other mapping file is loaded as a resource by the persistence provider. If a mapping file is specified, the classes and mapping information specified in the mapping file will be used One or more JAR files may be specified using the jar-file elements instead of, or in addition to the mapping files specified in the mapping-file elements. If specified, these JAR files will be searched for managed persistence classes, and any mapping metadata annotations found on them will be processed, or they will be mapped using the mapping annotation defaults defined by this specification. Such JAR files are specified relative to the directory or jar file that contains[82] the root of the persistence unit. Copyright LearningPatterns Inc. All rights reserved. 333

72 Session 7: Introduction to the JPA The EntityManager & Persistence Context An entity manager (abbreviated EM) object is used to interact with a database, to create, read, or write an entity An entity manager is configured to work with a specific data store It also contains the API to interact with the data store The EM also manages entity instances When the EM obtains an entity reference, the referenced object becomes a managed entity A persistence context is associated with an EM, and is comprised of the set of all managed entities within it Only one instance with a given persistent identity can exist within a persistence context e.g., if you get an event with id=25 twice from a persistent context, the 2 nd retrieval returns the same instance as the 1 st Entities don't interact with the database on their own, or contain the API to do so Applications must use an entity manager to interact with the DB Note that the idea of a persistence context is an important one A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance Within a persistence context, database identity and Java identity are the same Within a persistence context, the entity instances and their lifecycle are managed Copyright LearningPatterns Inc. All rights reserved. 334

73 Session 7: Introduction to the JPA EntityManager Interface EntityManager contains the entity manager API Defines methods to create and remove persistent entities, to find entities by their primary key, and to query over entities Some important EntityManager methods include: <T> T find(class<t> entityclass, Object primarykey): Find an entity by its primary key void persist(object entity): Make a new entity instance managed and persistent void refresh(object entity): Refresh the state of the instance from the database, overwriting changes made to the entity, if any void remove(object entity): Remove the entity instance Many more methods We'll cover many of them in the course Note that an entity manager is not thread safe It is meant to be used by a single thread at a time Entities are also intended to be accessed by a single thread at a time while they are being managed Really they also shouldn't be accessed by multiple threads when they are detached (which we talk about later) However, if you want to manage the thread safety in the entity instance for when it's detached, it's possible to do so It's not desirable It's better to make copies and merge the state back into a persistence context Notice that the find method is declared using Java generics This allows you to use it without casting the return type It's much more convenient than writing it in terms of Object and then casting the return value Copyright LearningPatterns Inc. All rights reserved. 335

74 Session 7: Introduction to the JPA Obtaining an Entity Manager An EntityManagerFactory provides EntityManagers An EntityManagerFactory is bound to a persistence unit It is thread-safe, and immutable In Java SE, you usually programmatically create the entity manager with an entity manager factory You also programmatically close it, and control the transactions (either directly, or with another container like Spring) We'll start with using JPA in a Java SE environment In a Java EE or Spring environment, the entity manager is generally injected using dependency injection Java EE also provides container managed transactions, and TX scoped entity managers making JPA very easy to use We'll look at this later You can obtain an EntityManager from an EntityManagerFactory Its behavior is controlled by the configuration properties Any EntityManager you get from a given factory will only manage instances as defined by that persistence unit When you create and close an entity manager, you are also creating and destroying the associated persistence context This just means that when the entity manager is closed, all entities in the persistence context become unmanaged We'll look at this more when we talk about detached entities When using EJB, you can also inject an entity manager by providing the name of the persistence unit This is the preferred way to obtain an entity manager when working with EJB Copyright LearningPatterns Inc. All rights reserved. 336

75 Session 7: Introduction to the JPA Injecting an EntityManager An EntityManager is usually injected when used in an EJB and the name of the persistence unit as shown in the example below The persistence unit is configured in persistence.xml The EntityManager instance can only manage instances as defined by the named persistence unit The example uses a stateless session façade around the JPA code // imports, etc. not public class EventServiceBean implements EventService EntityManager em; public void addevent(event event) { em.persist(event); } //... } We're using an EventService EJB to encapsulate operations involving Event objects This session bean façade is a common pattern It hides the details of working with the EntityManager It also hides details like the fact that the event id has to be extracted from the event after it is persisted since the id is generated In a Java SE environment, you generally use a bootstrap class called Persistence to read the configuration (persistence.xml) The Persistence type then produces the EntityManagerFactory, from which you can get EntityManagers You pass in the name of the persistence unit when creating the factory You will likely use a resource-local entity manager Copyright LearningPatterns Inc. All rights reserved. 337

76 Session 7: Introduction to the JPA Container-Managed Entity Manager An entity manager obtained by injection is called a containermanaged entity manager When a container injects an entity manager, its persistence context will be propagated within the current JTA transaction Within the JTA transaction all EntityManager references that are mapped to the same persistence unit will be associated with this same persistence context The lifetime of the persistence context is scoped to the lifetime of the JTA transaction Work is saved when the transaction ends When the transaction ends, the persistence context is destroyed This describes how a container-managed transactionscoped entity manager works There are other styles of operation (extended entity managers and application-managed entity managers) In Java EE environments, a JTA transaction typically involves calls across multiple components. Such components may often need to access the same persistence context within a single transaction. To facilitate such use of entity managers in Java EE environments, when an entity manager is injected into a component or looked up directly in JNDI its persistence context will automatically be propagated with the current JTA transaction, and the EntityManager references that are mapped to the same persistence unit will provide access to this same persistence context within the JTA transaction. This propagation of persistence context by the Java EE container avoids the need for the application to pass references to EntityManager instances from one component to another. An entity manager for which the container manages the persistence context in this manner is termed a container-managed entity manager. A container- managed entity manager s lifecycle is managed by the Java EE container. For a Java SE environment, where the application generally manages the entity manager, you can close an individual EntityManager instance by calling its close() method You can also close an EnityManagerFactory via its close() method Closing the factory closes all its EntityManagers Copyright LearningPatterns Inc. All rights reserved. 338

77 Session 7: Introduction to the JPA Retrieving Persistent Objects You can use the EntityManager.find() method to retrieve persistent objects from the database <T> T find(class<t> entityclass, Object primarykey) Returns the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance If an instance with the given primary key is already associated with the persistence context, return that instance // imports, etc. not public class EventServiceBean EntityManager em; public Event findbyid(long id) { return em.find(event.class,id); } //... } The find method takes the class of the entity being sought, and the id or primary key that identifies the entity It returns a managed entity that is initialized with the data from the database There is no cast required on the return value of the find method It is defined using a parameterized return type, to return the same type that was passed in If there is no object found with the given id, then find returns a null No exception is thrown Application code needs to check for nulls if this is a concern There should only be one managed instance with a given primary key in a persistence context The methods of EntityManager that retrieve instances enforce this rule Copyright LearningPatterns Inc. All rights reserved. 339

78 Lab 7.2 Using an Entity Class Lab 7.2 Using an Entity Class In this lab we will use the EntityManager to lookup MusicItem entities from data stored in a database Copyright LearningPatterns Inc. All rights reserved. 340

79 Session 7: Introduction to the JPA More About Mappings JPA Overview Mapping a Simple Class Entity Manager and Persistence Context More About Mappings Copyright LearningPatterns Inc. All rights reserved. 341

80 Session 7: Introduction to the JPA Default Mappings JPA has defaults for many basic types, as summarized in the table These types will by default be mapped to a database column with the attribute name, and and can map to the database types shown below The persistent fields and properties of an entity class are generically referred to in the JPA documentation as the attributes of the class Note that a particular Java type may be mapped to a number of different database types These are all supported by JPA, though there could conceivably be data loss depending on the Java type and database type For example, a string may be stored in a VARCHAR column that is not large enough for the length of the string, and is truncated If you use JPA to generate your DB schema, you can do things like specifying the length in the column declaration Copyright LearningPatterns Inc. All rights reserved. 342

Fast Track to EJB 3.0 and the JPA Using JBoss

Fast Track to EJB 3.0 and the JPA Using JBoss Fast Track to EJB 3.0 and the JPA Using JBoss The Enterprise JavaBeans 3.0 specification is a deep overhaul of the EJB specification that is intended to improve the EJB architecture by reducing its complexity

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 35 hours Price: $750 Delivery Option: Attend training via an on-demand, self-paced platform paired with personal instructor facilitation.

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 5 days Price: $2795 *California residents and government employees call for pricing. Discounts: We offer multiple discount options.

More information

Fast Track to EJB 3.0

Fast Track to EJB 3.0 Fast Track to EJB 3.0 using JBoss 4/5 and Eclipse LearningPatterns, Inc. Courseware JBoss is a registered trademark of Red Hat, Inc. in the U.S. and other countries. LearningPatterns has no affiliation

More information

"Charting the Course... Mastering EJB 3.0 Applications. Course Summary

Charting the Course... Mastering EJB 3.0 Applications. Course Summary Course Summary Description Our training is technology centric. Although a specific application server product will be used throughout the course, the comprehensive labs and lessons geared towards teaching

More information

Enterprise JavaBeans, Version 3 (EJB3) Programming

Enterprise JavaBeans, Version 3 (EJB3) Programming Enterprise JavaBeans, Version 3 (EJB3) Programming Description Audience This course teaches developers how to write Java Enterprise Edition (JEE) applications that use Enterprise JavaBeans, version 3.

More information

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7 CONTENTS Chapter 1 Introducing EJB 1 What is Java EE 5...2 Java EE 5 Components... 2 Java EE 5 Clients... 4 Java EE 5 Containers...4 Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

More information

Enterprise JavaBeans 3.1

Enterprise JavaBeans 3.1 SIXTH EDITION Enterprise JavaBeans 3.1 Andrew Lee Rubinger and Bill Burke O'REILLY* Beijing Cambridge Farnham Kbln Sebastopol Tokyo Table of Contents Preface xv Part I. Why Enterprise JavaBeans? 1. Introduction

More information

JVA-163. Enterprise JavaBeans

JVA-163. Enterprise JavaBeans JVA-163. Enterprise JavaBeans Version 3.0.2 This course gives the experienced Java developer a thorough grounding in Enterprise JavaBeans -- the Java EE standard for scalable, secure, and transactional

More information

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol Pro JPA 2 Mastering the Java Persistence API Mike Keith and Merrick Schnicariol Apress* Gootents at a Glance g V Contents... ; v Foreword _ ^ Afooyt the Author XXj About the Technical Reviewer.. *....

More information

Java EE 7: Back-End Server Application Development

Java EE 7: Back-End Server Application Development Oracle University Contact Us: Local: 0845 777 7 711 Intl: +44 845 777 7 711 Java EE 7: Back-End Server Application Development Duration: 5 Days What you will learn The Java EE 7: Back-End Server Application

More information

CO Java EE 7: Back-End Server Application Development

CO Java EE 7: Back-End Server Application Development CO-85116 Java EE 7: Back-End Server Application Development Summary Duration 5 Days Audience Application Developers, Developers, J2EE Developers, Java Developers and System Integrators Level Professional

More information

Developing Applications with Java EE 6 on WebLogic Server 12c

Developing Applications with Java EE 6 on WebLogic Server 12c Developing Applications with Java EE 6 on WebLogic Server 12c Duration: 5 Days What you will learn The Developing Applications with Java EE 6 on WebLogic Server 12c course teaches you the skills you need

More information

Module 8 The Java Persistence API

Module 8 The Java Persistence API Module 8 The Java Persistence API Objectives Describe the role of the Java Persistence API (JPA) in a Java EE application Describe the basics of Object Relational Mapping Describe the elements and environment

More information

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Java- EE Web Application Development with Enterprise JavaBeans and Web Services Java- EE Web Application Development with Enterprise JavaBeans and Web Services Duration:60 HOURS Price: INR 8000 SAVE NOW! INR 7000 until December 1, 2011 Students Will Learn How to write Session, Message-Driven

More information

Java EE 6: Develop Business Components with JMS & EJBs

Java EE 6: Develop Business Components with JMS & EJBs Oracle University Contact Us: + 38516306373 Java EE 6: Develop Business Components with JMS & EJBs Duration: 4 Days What you will learn This Java EE 6: Develop Business Components with JMS & EJBs training

More information

Java Enterprise Edition

Java Enterprise Edition Java Enterprise Edition The Big Problem Enterprise Architecture: Critical, large-scale systems Performance Millions of requests per day Concurrency Thousands of users Transactions Large amounts of data

More information

CO Java EE 6: Develop Database Applications with JPA

CO Java EE 6: Develop Database Applications with JPA CO-77746 Java EE 6: Develop Database Applications with JPA Summary Duration 4 Days Audience Database Developers, Java EE Developers Level Professional Technology Java EE 6 Delivery Method Instructor-led

More information

foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration

foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration contents foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration xix xxxii PART 1 GETTING STARTED WITH ORM...1 1 2 Understanding object/relational

More information

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject

More information

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java EJB Enterprise Java EJB Beans ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY Peter R. Egli 1/23 Contents 1. What is a bean? 2. Why EJB? 3. Evolution

More information

Deccansoft Software Services. J2EE Syllabus

Deccansoft Software Services. J2EE Syllabus Overview: Java is a language and J2EE is a platform which implements java language. J2EE standard for Java 2 Enterprise Edition. Core Java and advanced java are the standard editions of java whereas J2EE

More information

object/relational persistence What is persistence? 5

object/relational persistence What is persistence? 5 contents foreword to the revised edition xix foreword to the first edition xxi preface to the revised edition xxiii preface to the first edition xxv acknowledgments xxviii about this book xxix about the

More information

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics Spring & Hibernate Overview: The spring framework is an application framework that provides a lightweight container that supports the creation of simple-to-complex components in a non-invasive fashion.

More information

Introduction to JPA. Fabio Falcinelli

Introduction to JPA. Fabio Falcinelli Introduction to JPA Fabio Falcinelli Me, myself and I Several years experience in active enterprise development I love to design and develop web and standalone applications using Python Java C JavaScript

More information

V3 EJB Test One Pager

V3 EJB Test One Pager V3 EJB Test One Pager Overview 1. Introduction 2. EJB Testing Scenarios 2.1 EJB Lite Features 2.2 API only in Full EJB3.1 3. Document Review 4. Reference documents 1. Introduction This document describes

More information

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule Berner Fachhochschule Technik und Informatik EJB 3 Entities Course Multi Tier Business Applications with Java EE Prof. Dr. Eric Dubuis Berner Fachhochschule Biel Content Characteristics of entities Programming

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: 1,995 + VAT Course Description: This course provides a comprehensive introduction to JPA (the Java Persistence API),

More information

JPA Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

JPA Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule Berner Fachhochschule Technik und Informatik JPA Entities Course Multi Tier Business Applications with Java EE Prof. Dr. Eric Dubuis Berner Fachhochschule Biel Content Characteristics of entities Programming

More information

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~ 1 Component: Szyperski s definition of a component: A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can

More information

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP 2013 Empowering Innovation DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP contact@dninfotech.com www.dninfotech.com 1 JAVA 500: Core JAVA Java Programming Overview Applications Compiler Class Libraries

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject to GST/HST Delivery Options:

More information

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies J2EE - Version: 25 Developing Enterprise Applications with J2EE Enterprise Technologies Developing Enterprise Applications with J2EE Enterprise Technologies J2EE - Version: 25 5 days Course Description:

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: CDN$3275 *Prices are subject to GST/HST Course Description: This course provides a comprehensive introduction to JPA

More information

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand)

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Code: URL: D101074GC10 View Online The Developing Applications for the Java EE 7 Platform training teaches you how

More information

Fast Track to Java EE

Fast Track to Java EE Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This

More information

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition CMP 436/774 Introduction to Java Enterprise Edition Fall 2013 Department of Mathematics and Computer Science Lehman College, CUNY 1 Java Enterprise Edition Developers today increasingly recognize the need

More information

Oracle 10g: Build J2EE Applications

Oracle 10g: Build J2EE Applications Oracle University Contact Us: (09) 5494 1551 Oracle 10g: Build J2EE Applications Duration: 5 Days What you will learn Leading companies are tackling the complexity of their application and IT environments

More information

Implementing a Web Service p. 110 Implementing a Web Service Client p. 114 Summary p. 117 Introduction to Entity Beans p. 119 Persistence Concepts p.

Implementing a Web Service p. 110 Implementing a Web Service Client p. 114 Summary p. 117 Introduction to Entity Beans p. 119 Persistence Concepts p. Acknowledgments p. xvi Introduction p. xvii Overview p. 1 Overview p. 3 The Motivation for Enterprise JavaBeans p. 4 Component Architectures p. 7 Divide and Conquer to the Extreme with Reusable Services

More information

Java EE Architecture, Part Three. Java EE architecture, part three 1(69)

Java EE Architecture, Part Three. Java EE architecture, part three 1(69) Java EE Architecture, Part Three Java EE architecture, part three 1(69) Content Requirements on the Integration layer The Database Access Object, DAO Pattern Frameworks for the Integration layer Java EE

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

Deployment. See Packaging and deployment processes

Deployment. See Packaging and deployment processes Index A Address instance, 85 Aggregate average response time (AART), 282 Application assembler, deployment roles external requirements conflict and redundant, 343 dependencies, 341 references, 341 342

More information

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format. J2EE Development Detail: Audience www.peaksolutions.com/ittraining Java developers, web page designers and other professionals that will be designing, developing and implementing web applications using

More information

New Features in EJB 3.1

New Features in EJB 3.1 New Features in EJB 3.1 Sangeetha S E-Commerce Research Labs, Infosys Technologies Limited 2010 Infosys Technologies Limited Agenda New Features in EJB 3.1 No Interface View EJB Components in WAR Singleton

More information

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Enterprise Java Introduction Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Course Description This course focuses on developing

More information

Lightweight J2EE Framework

Lightweight J2EE Framework Lightweight J2EE Framework Struts, spring, hibernate Software System Design Zhu Hongjun Session 4: Hibernate DAO Refresher in Enterprise Application Architectures Traditional Persistence and Hibernate

More information

Developing Enterprise JavaBeans for Oracle WebLogic Server 12c (12.2.1)

Developing Enterprise JavaBeans for Oracle WebLogic Server 12c (12.2.1) [1]Oracle Fusion Middleware Developing Enterprise JavaBeans for Oracle WebLogic Server 12c (12.2.1) E55232-02 October 2015 This document is a resource for software developers who develop applications that

More information

POJOs to the rescue. Easier and faster development with POJOs and lightweight frameworks

POJOs to the rescue. Easier and faster development with POJOs and lightweight frameworks POJOs to the rescue Easier and faster development with POJOs and lightweight frameworks by Chris Richardson cer@acm.org http://chris-richardson.blog-city.com 1 Who am I? Twenty years of software development

More information

Java SE7 Fundamentals

Java SE7 Fundamentals Java SE7 Fundamentals Introducing the Java Technology Relating Java with other languages Showing how to download, install, and configure the Java environment on a Windows system. Describing the various

More information

Chapter 6 Enterprise Java Beans

Chapter 6 Enterprise Java Beans Chapter 6 Enterprise Java Beans Overview of the EJB Architecture and J2EE platform The new specification of Java EJB 2.1 was released by Sun Microsystems Inc. in 2002. The EJB technology is widely used

More information

Java J Course Outline

Java J Course Outline JAVA EE - J2SE - CORE JAVA After all having a lot number of programming languages. Why JAVA; yet another language!!! AND NOW WHY ONLY JAVA??? CHAPTER 1: INTRODUCTION What is Java? History Versioning The

More information

Exam Questions 1Z0-895

Exam Questions 1Z0-895 Exam Questions 1Z0-895 Java Platform, Enterprise Edition 6 Enterprise JavaBeans Developer Certified Expert Exam https://www.2passeasy.com/dumps/1z0-895/ QUESTION NO: 1 A developer needs to deliver a large-scale

More information

Courses For Event Java Advanced Summer Training 2018

Courses For Event Java Advanced Summer Training 2018 Courses For Event Java Advanced Summer Training 2018 Java Fundamentals Oracle Java SE 8 Advanced Java Training Java Advanced Expert Edition Topics For Java Fundamentals Variables Data Types Operators Part

More information

Topics in Enterprise Information Management

Topics in Enterprise Information Management Topics in Enterprise Information Management Dr. Ilan Kirsh JPA Basics Object Database and ORM Standards and Products ODMG 1.0, 2.0, 3.0 TopLink, CocoBase, Castor, Hibernate,... EJB 1.0, EJB 2.0: Entity

More information

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline Advanced Java Database Programming JDBC overview SQL- Structured Query Language JDBC Programming Concepts Query Execution Scrollable

More information

Java SE 8 Fundamentals

Java SE 8 Fundamentals Oracle University Contact Us: +52 1 55 8525 3225 Java SE 8 Fundamentals Duration: 5 Days What you will learn This Java SE 8 Fundamentals training introduces you to object-oriented programming using the

More information

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module Java Platform, Enterprise Edition 5 (Java EE 5) Core Java EE Java EE 5 Platform Overview Java EE Platform Distributed Multi tiered Applications Java EE Web & Business Components Java EE Containers services

More information

JVA-563. Developing RESTful Services in Java

JVA-563. Developing RESTful Services in Java JVA-563. Developing RESTful Services in Java Version 2.0.1 This course shows experienced Java programmers how to build RESTful web services using the Java API for RESTful Web Services, or JAX-RS. We develop

More information

Business Component Development with EJB Technology, Java EE 5

Business Component Development with EJB Technology, Java EE 5 Business Component Development with EJB Technology, Java EE 5 Student Guide SL-351-EE5 REV D.2 D61838GC10 Edition 1.0 D62447 Copyright 2008, 2009, Oracle and/or its affiliates. All rights reserved. Disclaimer

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

JPA. Java persistence API

JPA. Java persistence API JPA Java persistence API JPA Entity classes JPA Entity classes are user defined classes whose instances can be stored in a database. JPA Persistable Types The term persistable types refers to data types

More information

"Web Age Speaks!" Webinar Series

Web Age Speaks! Webinar Series "Web Age Speaks!" Webinar Series Java EE Patterns Revisited WebAgeSolutions.com 1 Introduction Bibhas Bhattacharya CTO bibhas@webagesolutions.com Web Age Solutions Premier provider of Java & Java EE training

More information

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14.

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14. Oracle 1z0-861 Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam Practice Test Version: 14.22 QUESTION NO: 1 A developer wants to create a business interface for

More information

OracleAS 10g R3: Build J2EE Applications II

OracleAS 10g R3: Build J2EE Applications II OracleAS 10g R3: Build J2EE Applications II Volume I Student Guide D18380GC10 Edition 1.0 April 2006 D45763 Authors David Loo Glenn Stokol Technical Contributors and Reviewers Michael Burke Dr. Ken Cooper

More information

Java EE Architecture, Part Three. Java EE architecture, part three 1(57)

Java EE Architecture, Part Three. Java EE architecture, part three 1(57) Java EE Architecture, Part Three Java EE architecture, part three 1(57) Content Requirements on the Integration layer The Database Access Object, DAO Pattern Frameworks for the Integration layer Java EE

More information

Erik Dörnenburg JAOO 2003

Erik Dörnenburg JAOO 2003 Persistence Neutrality using the Enterprise Object Broker application service framework Erik Dörnenburg JAOO 2003 Sample project Simple application Heavy client One business entity Basic operations Person

More information

Architect Exam Guide. OCM EE 6 Enterprise. (Exams IZO-807,1ZO-865 & IZO-866) Oracle Press ORACLG. Paul R* Allen and Joseph J.

Architect Exam Guide. OCM EE 6 Enterprise. (Exams IZO-807,1ZO-865 & IZO-866) Oracle Press ORACLG. Paul R* Allen and Joseph J. ORACLG Oracle Press OCM Java@ EE 6 Enterprise Architect Exam Guide (Exams IZO-807,1ZO-865 & IZO-866) Paul R* Allen and Joseph J. Bambara McGraw-Hill Education is an independent entity from Oracle Corporation

More information

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product.

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product. Oracle EXAM - 1Z0-895 Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam Buy Full Product http://www.examskey.com/1z0-895.html Examskey Oracle 1Z0-895 exam demo product is here for you to test

More information

Java EE Architecture, Part Two. Java EE architecture, part two 1

Java EE Architecture, Part Two. Java EE architecture, part two 1 Java EE Architecture, Part Two Java EE architecture, part two 1 Content Requirements on the Business layer Framework Independent Patterns Transactions Frameworks for the Business layer Java EE architecture,

More information

OCP JavaEE 6 EJB Developer Study Notes

OCP JavaEE 6 EJB Developer Study Notes OCP JavaEE 6 EJB Developer Study Notes by Ivan A Krizsan Version: April 8, 2012 Copyright 2010-2012 Ivan A Krizsan. All Rights Reserved. 1 Table of Contents Table of Contents... 2 Purpose... 9 Structure...

More information

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently. Gang of Four Software Design Patterns with examples STRUCTURAL 1) Adapter Convert the interface of a class into another interface clients expect. It lets the classes work together that couldn't otherwise

More information

Building the Enterprise

Building the Enterprise Building the Enterprise The Tools of Java Enterprise Edition 2003-2007 DevelopIntelligence LLC Presentation Topics In this presentation, we will discuss: Overview of Java EE Java EE Platform Java EE Development

More information

/ / JAVA TRAINING

/ / JAVA TRAINING www.tekclasses.com +91-8970005497/+91-7411642061 info@tekclasses.com / contact@tekclasses.com JAVA TRAINING If you are looking for JAVA Training, then Tek Classes is the right place to get the knowledge.

More information

Appendix A - Glossary(of OO software term s)

Appendix A - Glossary(of OO software term s) Appendix A - Glossary(of OO software term s) Abstract Class A class that does not supply an implementation for its entire interface, and so consequently, cannot be instantiated. ActiveX Microsoft s component

More information

Using JNDI from J2EE components

Using JNDI from J2EE components Using JNDI from J2EE components Stand-alone Java program have to specify the location of the naming server when using JNDI private static InitialContext createinitialcontext() throws NamingException {

More information

Data Management in Application Servers. Dean Jacobs BEA Systems

Data Management in Application Servers. Dean Jacobs BEA Systems Data Management in Application Servers Dean Jacobs BEA Systems Outline Clustered Application Servers Adding Web Services Java 2 Enterprise Edition (J2EE) The Application Server platform for Java Java Servlets

More information

POJOs in Action DEVELOPING ENTERPRISE APPLICATIONS WITH LIGHTWEIGHT FRAMEWORKS CHRIS RICHARDSON MANNING. Greenwich (74 w. long.)

POJOs in Action DEVELOPING ENTERPRISE APPLICATIONS WITH LIGHTWEIGHT FRAMEWORKS CHRIS RICHARDSON MANNING. Greenwich (74 w. long.) POJOs in Action DEVELOPING ENTERPRISE APPLICATIONS WITH LIGHTWEIGHT FRAMEWORKS CHRIS RICHARDSON MANNING Greenwich (74 w. long.) contents PART 1 1 preface xix acknowledgments xxi about this book xxiii about

More information

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes Java CORE JAVA Core Java Programing (Course Duration: 40 Hours) Introduction to Java What is Java? Why should we use Java? Java Platform Architecture Java Virtual Machine Java Runtime Environment A Simple

More information

Dali Java Persistence Tools

Dali Java Persistence Tools Dali Java Persistence Tools User Guide Release 3.2 September 2012 Dali Java Persistence Tools User Guide Release 3.2 Copyright 2011, 2012, Oracle and/or its affiliates. All rights reserved. The Eclipse

More information

Object-relational mapping EJB and Hibernate

Object-relational mapping EJB and Hibernate T A R T U Ü L I K O O L MATEMAATIKA-INFORMAATIKATEADUSKOND Arvutiteaduse instituut Infotehnoloogia eriala Aleksandr Tkatšenko Object-relational mapping EJB and Hibernate Referaat aines Tarkvaratehnika

More information

Stateful Session Beans

Stateful Session Beans Berner Fachhochschule Technik und Informatik Stateful Session Beans Course Multi Tier Business Applications with Java EE Prof. Dr. Eric Dubuis Berner Fachhochschule Biel Content Characteristics of stateful

More information

Comparative Analysis of EJB3 and Spring Framework

Comparative Analysis of EJB3 and Spring Framework Comparative Analysis of EJB3 and Spring Framework Janis Graudins, Larissa Zaitseva Abstract: The paper describes main facilities of EJB3 and Spring Framework as well as the results of their comparative

More information

ADVANCED JAVA TRAINING IN BANGALORE

ADVANCED JAVA TRAINING IN BANGALORE ADVANCED JAVA TRAINING IN BANGALORE TIB ACADEMY #5/3 BEML LAYOUT, VARATHUR MAIN ROAD KUNDALAHALLI GATE, BANGALORE 560066 PH: +91-9513332301/2302 www.traininginbangalore.com 2EE Training Syllabus Java EE

More information

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1 Umair Javed 2004 J2EE Based Distributed Application Architecture Overview Lecture - 2 Distributed Software Systems Development Why J2EE? Vision of J2EE An open standard Umbrella for anything Java-related

More information

J2EE Interview Questions

J2EE Interview Questions 1) What is J2EE? J2EE Interview Questions J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces

More information

SUN Sun Certified Enterprise Architect for J2EE 5. Download Full Version :

SUN Sun Certified Enterprise Architect for J2EE 5. Download Full Version : SUN 310-052 Sun Certified Enterprise Architect for J2EE 5 Download Full Version : http://killexams.com/pass4sure/exam-detail/310-052 combination of ANSI SQL-99 syntax coupled with some company-specific

More information

Spring Interview Questions

Spring Interview Questions Spring Interview Questions By Srinivas Short description: Spring Interview Questions for the Developers. @2016 Attune World Wide All right reserved. www.attuneww.com Contents Contents 1. Preface 1.1. About

More information

Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics:

Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics: Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics: EJB 3 entities Java persistence API Mapping an entity to a database table

More information

Introduction to Session beans. EJB - continued

Introduction to Session beans. EJB - continued Introduction to Session beans EJB - continued Local Interface /** * This is the HelloBean local interface. * * This interface is what local clients operate * on when they interact with EJB local objects.

More information

Migrating traditional Java EE applications to mobile

Migrating traditional Java EE applications to mobile Migrating traditional Java EE applications to mobile Serge Pagop Sr. Channel MW Solution Architect, Red Hat spagop@redhat.com Burr Sutter Product Management Director, Red Hat bsutter@redhat.com 2014-04-16

More information

IBM. Enterprise Application Development with IBM Web Sphere Studio, V5.0

IBM. Enterprise Application Development with IBM Web Sphere Studio, V5.0 IBM 000-287 Enterprise Application Development with IBM Web Sphere Studio, V5.0 Download Full Version : http://killexams.com/pass4sure/exam-detail/000-287 QUESTION: 90 Which of the following statements

More information

TOPLink for WebLogic. Whitepaper. The Challenge: The Solution:

TOPLink for WebLogic. Whitepaper. The Challenge: The Solution: Whitepaper The Challenge: Enterprise JavaBeans (EJB) represents a new standard in enterprise computing: a component-based architecture for developing and deploying distributed object-oriented applications

More information

What data persistence means? We manipulate data (represented as object state) that need to be stored

What data persistence means? We manipulate data (represented as object state) that need to be stored 1 Data Persistence What data persistence means? We manipulate data (represented as object state) that need to be stored persistently to survive a single run of the application queriably to be able to retrieve/access

More information

Index. setmaxresults() method, 169 sorting, 170 SQL DISTINCT query, 171 uniqueresult() method, 169

Index. setmaxresults() method, 169 sorting, 170 SQL DISTINCT query, 171 uniqueresult() method, 169 Index A Annotations Hibernate mappings, 81, 195 Hibernate-specific persistence annotations Immutable annotation, 109 natural ID, 110 Hibernate XML configuration file, 108 JPA 2 persistence (see JPA 2 persistence

More information

Apache OpenJPA User's Guide

Apache OpenJPA User's Guide Apache OpenJPA User's Guide Apache OpenJPA User's Guide 1. Introduction 1 1. OpenJPA.. 3 1.1. About This Document. 3 2. Java Persistence API 4 1. Introduction. 9 1.1. Intended Audience 9 1.2. Lightweight

More information

Seam 3. Pete Muir JBoss, a Division of Red Hat

Seam 3. Pete Muir JBoss, a Division of Red Hat Seam 3 Pete Muir JBoss, a Division of Red Hat Road Map Introduction Java EE 6 Java Contexts and Dependency Injection Seam 3 Mission Statement To provide a fully integrated development platform for building

More information

ΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ

ΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ ΠΑΡΑΡΤΗΜΑ «Β» ΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ Α/Α ΠΕΡΙΓΡΑΦΗ ΕΚΠΑΙΔΕΥΣΗΣ ΘΕΜΑΤΙΚΕΣ ΕΝΟΤΗΤΕΣ 1. Java SE8 Fundamentals What Is a Java Program? Introduction to Computer Programs Key Features of the Java Language

More information

JPA The New Enterprise Persistence Standard

JPA The New Enterprise Persistence Standard JPA The New Enterprise Persistence Standard Mike Keith michael.keith@oracle.com http://otn.oracle.com/ejb3 About Me Co-spec Lead of EJB 3.0 (JSR 220) Java EE 5 (JSR 244) expert group member Co-author Pro

More information

SCBCD EXAM STUDY KIT. Paul Sanghera CX JAVA BUSINESS COMPONENT DEVELOPER CERTIFICATION FOR EJB MANNING. Covers all you need to pass

SCBCD EXAM STUDY KIT. Paul Sanghera CX JAVA BUSINESS COMPONENT DEVELOPER CERTIFICATION FOR EJB MANNING. Covers all you need to pass CX-310-090 SCBCD EXAM STUDY KIT JAVA BUSINESS COMPONENT DEVELOPER CERTIFICATION FOR EJB Covers all you need to pass Includes free download of a simulated exam You will use it even after passing the exam

More information

A COMPONENT BASED ONLINE ORDERING SYSTEM USING ENTERPRISE JAVABEANS 3.0

A COMPONENT BASED ONLINE ORDERING SYSTEM USING ENTERPRISE JAVABEANS 3.0 A COMPONENT BASED ONLINE ORDERING SYSTEM USING ENTERPRISE JAVABEANS 3.0 AUTHOR: JAMES OSBORNE SUPERVISOR: DR. KUNG KIU LAU 2 MAY 2007 ABSTRACT Title: A Component Based Online Ordering System Using Enterprise

More information