Ejb Java2
Ejb Java2
Applies to:
Web Dynpro for Java applications for SAP NetWeaver CE 7.11
Summary
This tutorial shows you how to store and read data via an abstract database layer managed by the Java
Persistence API using the Web Dynpro framework. You will be introduced into developing different
components such as Dictionary DC, Enterprise Java Bean 3.0 Module, JPA Entity, Web services and finally
Web Dynpro Java as UI layer.
Prerequisites
- Java JDK 1.5.0_13 is installed on your client and is identical to that of the Application Server
- Java Environment Variables are set properly
- Access to an SAP NetWeaver Application Server for Java CE 7.11
- Installed SAP NetWeaver Developer Studio SAP NetWeaver CE 7.11
- Basic knowledge of Web Dynpro for Java
Details
Level of complexity: Beginner
Time required for completion: 60 min.
Author Bio
Martin Clabunde is studying computer science at the University of Applied Science Worms and
works as a working student in Product Management for SAP NetWeaver User Interaction - Web
Dynpro for Java.
Table of Contents
Overview .........................................................................................................................................................3
Scenario ..........................................................................................................................................................3
Glossary ..........................................................................................................................................................4
Create the Dictionary Development Component ................................................................................................5
Create the database Connection Profile .........................................................................................................5
The Enterprise Java Bean 3.0 Module............................................................................................................6
Create the EJB Module DC..........................................................................................................................................7
Enable the JPA Facet in the Modify Faceted Project dialog.........................................................................................8
Configure the JPA Facet ..............................................................................................................................................8
Provide a JPA Entity (detailed) ....................................................................................................................................9
Configure the Entity in the JPA Perspective...............................................................................................................10
Apply Forward Mapping .............................................................................................................................................12
The EJB Session Bean 3.0 ...........................................................................................................................13
Create the EJB Session Bean 3.0..............................................................................................................................13
Implement the business methods (detailed)...............................................................................................................13
Add the business methods to the local interface........................................................................................................15
Configure the Persistence Unit Name and the jta-data-source ..................................................................................16
The Java EE Enterprise Application Archive ................................................................................................17
Create an Enterprise Application Archive ..................................................................................................................17
Enable the SAP Data Source Aliases Provider Module .............................................................................................18
Create a Data Source Alias........................................................................................................................................18
Expose the session bean's local interface as a Web Service ....................................................................................19
Deploy the Dictionary DC..............................................................................................................................20
Deploy the Enterprise Application Archive DC .............................................................................................20
Consuming your Web Service in Web Dynpro .............................................................................................20
Create the Web Dynpro DC ..........................................................................................................................21
Create the Adaptive Web Service Model ...................................................................................................................21
Create the Web Dynpro Application with default components ...................................................................................22
Apply the Service Controller Code Template .............................................................................................................23
Map the View Controller Context to the Custom Controller Context ..........................................................................24
Layout the view using templates ................................................................................................................................25
Display available customer records in a Table UI element ........................................................................................25
Provide an input form to add a new customer............................................................................................................26
Add an Action Button to the input form to submit the data .........................................................................................27
Deploy new Archive and Run........................................................................................................................28
Result ............................................................................................................................................................28
Related Content ............................................................................................................................................29
Copyright...........................................................................................................................................................30
Overview
The objective of this tutorial is to give you a short introduction on how to develop your own Web Service in
the Java Enterprise Edition 5 (Java EE) world using the Java Persistence API (JPA) and the Web Dynpro for
Java framework on the presentation layer side. The scenario encapsulates the business logic as Web
Service using the Simple Object Access Protocol (SOAP) to communicate with the clients over the net. The
Web Service will neither being published to any repository nor references a Service Group since Logical
Destinations became deprecated with Enhancement Package 1 for SAP NetWeaver 7.1 Java.
This tutorial focuses on a basic concept needed in a simple local scenario only.
The Web Dynpro application which you are going to create lets you submit a simple form with two input
fields. The submitted data then will be stored in the underlying default database and will be displayed in a
Web Dynpro Table UI element using the Web Service methods implemented.
The illustration on the next side outlines a simplified overview on how the used components interact among
each other. This illustration is not intended to cover the real world (environment and wiring).
For more detailed information please refer to the Related Content area at the end of this document. This
section provides some hyperlinks to further reading in the SAP Developer Network (SDN) and the
Developer's Guide in the SAP Library.
Note: This tutorial is only a simple getting started tutorial and is not intended for productive use.
Scenario
Starting with the Enterprise Java Bean 3.0 (EJB) Module Development Component (DC), the Java
Persistence API (JPA) facet must be enabled first. The JPA then helps you managing the entities very
comfortable. Entities are just Plain Old Java Objects (POJOs), i.e. Java classes. These entities are managed
by the JPA within the EJB container. That scenario is called Container Managed Persistence (CMP).
Entities are controlled by the Entity Manager provided by the JPA framework. The instance of the Entity
Manager is injected to a field of a Stateless Session Bean (SSB), where the business logic is implemented,
and must be associated with a persistence context. The set of entities that can be managed by the given
Entity Manager instance is defined by a persistence unit.
A client accesses the SSB thru its Service Endpoint Interface (SEI), which is the SSB's local interface. The
transactional behavior can be configured slightly in a CMP scenario using annotation.
The EJB Module must reside in an Enterprise Application Archive (EAR) which can be deployed to the SAP
Application Server (SAP AS) Java. Modules are not deployable standalone. Once the EAR is deployed the
Web Service Description Language (WSDL) file is generated out of the annotations found in the entities, the
SSB and its local interface. A Web Service is made of annotations only.
The Dictionary acts as an abstraction layer and is a generic metadata representation of a real data source. It
provides special functionalities and is accessible thru a connection profile specified. Once it is deployed to
the Application Server the defined table schema is applied to the real data source and can be accessed. The
'missing' link between the underlying data source and the persistence context is described by a logical name,
the data-source-alias which maps to a real data source name.
Once both DCs, the EAR and the Dictionary, are deployed to the SAP AS and the WSDL file is accessible
via URL, the Web Dynpro DC will be created. The Adaptive Web Service (AWS) Model is then built up from
the given WSDL file and the form can be arranged.
Glossary
3. Press Next > open the 'Local Development' branch and select the MyComponents Software
Component (SC) and press Next >.
4. Name your new DC mydict, press Next > and confirm with Finish. Stay in the Java EE
Perspective.
You should see your Dictionary DC mydict in the Project Explorer now.
5. Browse for your dictionary DC mydict if it hasn't been chosen automatically yet and confirm with
Finish.
The new Connection Profile MYDICT will be shown directly under the Databases branch.
The Data Source Explorer view provides information and functions about the connection profiles, their Schemas and creating new
ones as well as support for the Data Definition Language (DDL) .
2. Select the EJB Module within the J2EE branch and press Next >.
You should be able to see both DCs, mydict and myejb, in the Project Explorer view.
Facets define characteristics and requirements for Java EE projects (apart from Java projects) and are used as part of
the runtime configuration
Enabling the Java Persistence API (JPA) within your EJB Container gives you the option to let your entity
beans be controlled by the Entity Manager. An instance of the Entity Manager will be directly injected 1 into a
private field of your session bean at runtime and can then be used to manage your entities. The Entity
Manager provides functions for creating, finding, removing, executing and fetching your named or dynamic
queries (prepared statements). The transactional behavior can be controlled via annotation attributes or
manually (Bean Managed Persistence).
1
This technique is described by the design pattern Dependency Injection.
Browse your EJB Module DC structure. It should have an additional branch where all your entities then will
be listed. Later on you will change this name of the node
4. In the Entity Properties dialog deselect the Table name: Use default option and provide a table
name that fulfills the naming convention, such as TMP_CUSTOMER.
5. Use the Add… Button to provide some fields as shown in the next screenshot and select the ID field
as Primary Key and confirm with Finish.
The Entity Properties
dialog helps you define your
basic entity properties.
Your entity should be created now. Don't worry about the error that appears in the JPA Validator. This is due
to the missing customer table definition in your dictionary. After applying some additional configuration steps
to the entity, you are going to fix that using JPA-Tool, which generates and executes the appropriate DDL
script.
Browse the myejb DC. It should looks like the following screenshot:
6. Copy and paste following code under the @Table annotation of the entity.
@XmlAccessorType(XmlAccessType.PROPERTY)
Note: This step is important because the Java Architecture for XML Binding (JAXB) layer expects XML
annotations on public members by default. In the previous step you put an XML annotation in front
of a property. At a later stage, when your Web Service is accessible via the URL, you can search
within the generated WSDL file for the parameter nillable="true" if you want.
7. To insert a named query, select your Customer entity in the Outline view and choose Java EE
Annotations Æ Entity Æ NamedQuery
This adds the @NamedQuery annotation with default placeholders right on top of your class
definition.
8. Specify the query parameter to fetch all available customers in the @NamedQuery(…).
…query = "Select c from Customer c"…
9. Name your query "getAllCustomers".
10. Delete the hints parameter - you won't need it in this scenario.
11. Organize Imports by pressing Ctrl+Shift+O.
12. Safe your entity by choosing Save All from the File menu or by pressing Ctrl+Shift+S.
Your entity's definition should look like the screenshot section below, apart from the package and import
statements and methods:
2. In the Outline view, right-click the em : EntityManager entry listed within your session bean and
choose Java EE Annotations Æ General Æ PersistenceContext from the context menu.
: :
: :
The annotation will be inserted in the line of code associated with the selection in the Outline.
3. 3. Change the unitName parameter of the @PersistenceContext annotation from its default value to
myUnitName.
Note: This name identifier is case sensitive and will be specified in the persistence.xml file later on.
4. Organize imports using Ctrl+Shift+O and select the appropriate imports as shown in the
screenshots:
a.
b.
2. Right-click one of the selected methods without losing the selection and choose
EJB methods Æ Add to Local Interfaces from the context menu.
The selected methods will be added to the local interface of your session bean.
Open the the Java Editor and have a look at your session bean's local interface.
3. Right-click the persistence-unit element and add the jta-data-source element by choosing
Add Child Æ jta-data-source from the context menu.
2. Select the Enterprise Application in the J2EE branch and press Next >.
2. Open the data-source-aliases.xml file by choosing Open from the context menu or press F3 key.
Expand the Aliases folder to the default ALIAS and change its name to MYDICT.
2. Right-click your session bean MySessionBean and choose Web Services Æ Create Web Service
from the context menu.
3. In the Web Services dialog set the Slider value to Develop Service.
I. Filter for your bean's interface by typing *my* into the filter input field.
II. Select the found MySessionLocal interface and press OK to close the dialog.
6. Back in the Web Service dialog go for the Web Service customizations dialog by pressing Next >.
7. Leave the default values unchanged and note your WSDL URL preview if you want.
http://<host>:<port>/MySessionService/MySessionBean?wsdl
8. Confirm all dialogs with Finish.
9. Have a look at your bean and its local interface. The corresponding annotations should be added.
Note: At a later stage, when you develop your first larger scenario with more than a single entity and more complex
relationships, you have to consider that there are some limitations using Web Services in conjunction with ORM i.
e Object/Relational Impedance. All this means is that if you are going to try to build up an XML/SOAP file from
particular entity relationships you will face an infinite xml file structure. The JAXB layer redeems that with an
appropriate exception message. Typically this occurs on bidirectional relations between entities. You can avoid this
by hiding the relevant fields and/or properties with the @XmlTransient annotation. However, this may not be
sufficient. Please refer to further reading.
Note: If you are accessing the internet via proxy, this must be configured accordingly under preferences.
5. In the Create Service Group dialog select No service group configuration and press Next >.
6. In the Logical Destinations dialog select No logical destinations and confirm with Finish.
Note: In this tutorial you do not need to define either logical destinations or service groups. But bear in mind
that since Logical Destinations are deprecated, it is recommended that you make use of Service Groups
instead. Service Groups for consumer applications are maintained in the Application Communication module of
the NetWeaver Administrator. A physical Provider System must be assigned to the relevant Service Group.
4. In the Define Used Models dialog press the Add… button and select your Model1.
2. Select the Service Controller template from the dialog that opens and press Next >.
5. The template even provides an execution method for the request model class. Leave the proposal
unchanged and confirm with Finish.
6. Right-click the automatically created Model1Controller and choose Template Æ Apply… from the
context menu again.
3. Drag both Request-Nodes, one after another, from the right to the left pane and drop them onto the
MyCompView context-root node and select all available nodes as shown in the screenshots below.
Result: The context of your view controller context is mapped to the Model1Controller context.
2. In the Outline view select the RootElement and choose Apply Template from the context menu.
3. Select the Table template from the Select Template dialog that opens and press Next >.
5. Sort the table columns by your needs using the up/down buttons and confirm with Finish.
6. Open MyCompView in the Java Editor. Choose Open Æ Java Editor from the context menu and
copy and paste following code between the @begin and @end tags within the wdDoModifyView()-
method.
if( firstTime ){
wdThis.wdGetModel1ControllerController().executeGetCustomers();
}
The Form will be created in a Transparent Container UI element and added to the Outline view.
5. Navigate to the button action implementation onActionSaveCustomer(…) and insert the following
line of code right after the …executeSetCustomer() method call.
wdThis.wdGetModel1ControllerController().executeGetCustomers();
6. In the Outline view expand the TransContainer_0 UI element and switch to the Properties tab in
the lower screen area.
7. Change the layout property of TransContainer_0 to MatrixLayout.
8. Set the each layout property of FirstName_0_label, LastName_0_label and the Button to
MatrixHeadData. Multiple selections are also possible by holding the Ctrl key while selecting each
UI element in the Outline view.
9. Delete the DefaultTextView element in the Outline view.
10. Save All. Ctrl+Shift+S
Your layout should look like the screenshot below:
Result
Pressing the Save Customer
Action Button of the form causes
the framework to persist the given
data. The table shows the new
record instantly.
Related Content
Adobe PDF
Creating Your First Web Dynpro Application
Basics of JPA - Defining and Using Relationships
Basics of JPA - Understanding the Entity Manager
SAP Library
Component Model
Developing Java EE 5 Applications
Using JPA in the Persistence Layer
Developing User Interfaces with Web Dynpro for Java
Copyright
© 2008 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG.
The information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors.
Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries,
zSeries, System i, System i5, System p, System p5, System x, System z, System z9, z/OS, AFP, Intelligent Miner, WebSphere,
Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, POWER5+, OpenPower and PowerPC are trademarks or registered trademarks of
IBM Corporation.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems
Incorporated in the United States and/or other countries.
Oracle is a registered trademark of Oracle Corporation.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of
Citrix Systems, Inc.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts
Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by
Netscape.
MaxDB is a trademark of MySQL AB, Sweden.
SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All
other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves
informational purposes only. National product specifications may vary.
These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP
Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or
omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the
express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an
additional warranty.
These materials are provided “as is” without a warranty of any kind, either express or implied, including but not limited to, the implied
warranties of merchantability, fitness for a particular purpose, or non-infringement.
SAP shall not be liable for damages of any kind including without limitation direct, special, indirect, or consequential damages that may
result from the use of these materials.
SAP does not warrant the accuracy or completeness of the information, text, graphics, links or other items contained within these
materials. SAP has no control over the information that you may access through the use of hot links contained in these materials and
does not endorse your use of third party web pages nor provide any warranty whatsoever relating to third party web pages.
Any software coding and/or code lines/strings (“Code”) included in this documentation are only examples and are not intended to be
used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of
certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors
or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent.