1 / 85

Java Web Development with NetBeans IDE

Java Web Development with NetBeans IDE. -- Kai Qian. Chapter 7 Java Persistence API. Objectives. Basics of Java Persistence API (JPA) Java Entity Beans JPA Entity Relationship Map. Entity Classes.

kristyn
Download Presentation

Java Web Development with NetBeans IDE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Web Development with NetBeans IDE --Kai Qian Chapter 7 Java Persistence API

  2. Objectives • Basics of Java Persistence API (JPA) • Java Entity Beans • JPA Entity Relationship Map

  3. Entity Classes • Entity classes make up the model in the MVC design pattern. Essentially an entity is a POJO that holds data for the purposes of saving that data in a database.

  4. Entity Classes, cont. • An entity class has the following characteristics: 1. The class is annotated with the @Entity annotation so that the Enterprise container will recognize it as an entity class. 2. The class's member variables should not be public. Access to the variables should be through accessor (getter) and mutator (setter) methods. 3. The class should have a no-argument constructor. It may have other constructors, but the no-argument constructor must exist. 4. The member variables that will be persisted to a database should be primitive types, serializable classes (such as java.util.Date), or classes that implement the Collection interface (like Lists or Sets).

  5. Entity Ids and Primary Keys • Just as every database table needs a primary key, every entity class needs an Id field, specified by the @Id annotation. • The value in the object's @Id variable will become the primary key in the database table when the object is saved to the database. • It will be used again to identify the particular row in the database table where the entity is stored when it is read from the database.

  6. Entity Ids and Primary Keys, contd. • A primary key class must follow some simple conventions: 1. It must have a no-argument constructor. 2. It must be declared public and the fields or properties declared public or protected. 3. It must implement the Serializable interface. 4. It must implement an equals(Object otherObject) method and the hashCode() method. 5. The names of the fields or properties must match the names in the entity it represents exactly.

  7. Entity Relationships • It would be difficult to model an entire application around a single entity class. • A non-trivial application will have several entity classes making up the data model. • The Java objects represent relationships by maintaining references to other objects to which they are related.

  8. Multiplicity • Multiplicity refers to the number of object instances that can participate in a relationship. • The objects relate to each other in the following ways: Each Student takes many Courses Each Course has many Students enrolled in it Each Grade is assigned to only one Student Each Student may be assigned several Grades (from taking several courses) Each Student has a single GPA Each GPA belongs to a specific Student

  9. Multiplicity, contd.

  10. Multiplicity, contd. • One To One The Student and GPA objects participate in a one to one relationship. A one to one relationship is signaled by annotating the appropriate field or property with the @OneToOne annotation. • One To Many The Student object contains a List of Grade objects. To declare a one to many relationship, annotate the Collection field or property with the @OneToMany annotation.

  11. Multiplicity, contd. • Many To One The many to one relationship is the direct inverse of the one to many relationship. the Student field or property in the Grade object would be annotated with the @ManyToOne annotation. • Many To Many The Student and Course entities have a many to many relationship. To distinguish a many to many relationship from a one to many relationship the @ManyToMany annotation is used on the corresponding Collection field or property.

  12. Directionand Ownership in Relationships • Relationships between entities may be unidirectional or bidirectional. • When bidirectional relationships are used one of the entities must be specified as the owner. • Ownership simply means that one of the entities is responsible for maintaining the relationship. • To make clear which side is the owning side of a relationship we added some additional parameters to the side that does not own the relationship.

  13. Persistence context and EntityManager • The persistence context is the collection of managed entities in a particular data store. • The persistence context is manipulated by means of the EntityManager interface.

  14. Entity Lifecycle

  15. Persistence context and EntityManager, contd. • Entities exist in one of four distinct states: detached, managed, new, or removed • When you create a new instance of an entity class you have an entity in the new state. • Once an entity has become managed it is represented in the data store and is associated with a persistence context.

  16. Manipulating Entities • Relational databases support four basic operations: create, read, update, and delete (often abbreviated as CRUD). • The <T> T EntityManager.find(Class<T> entityClass, Object primaryKey) method corresponds to a database's Read operation. • <T> T EntityManager.merge(T entity) performs the JPA version of the database's Update operation. • The final database operation, Delete, is performed by the void EntityManager.remove(Object entity) method.

  17. Finding Entities • While performing CRUD operations makes the EntityManager a very useful tool, there is one more method that makes it invaluable. The Query EntityManager.createQuery(String qlString) method plays an important role in retrieving data. • The major difference between JPQL and SQL is that SQL is designed to retrieve specific rows from a table made up of columns specified in the query.

  18. Chapter 7 SOAPObjectives • Describe what SOAP is used for and the concept behind SOAP • Identify what the SOAP specification is composed of and where it can be found • Describe the SOAP Message Exchange Patterns • Describe the structure of the SOAP message and explain all of its parts • Describe how data is encoded in a SOAP message • Provide a step-by-step example of how to program with SOAP in Java

  19. SOAP Overview • SOAP is a specification that describes a standard structure for encoding and packaging data and exchanging that data between distributed software applications • SOAP provides interoperability between applications written in different programming languages and/or running on different platforms • SOAP achieves interoperability through the use of the eXtensible Markup Language (XML) and by remaining independent of other protocols • Since SOAP is based on XML therefore, SOAP is text-based. Past attempts at a standard protocol for cross-platform interoperability have used a binary format (e.g., DCE-RPC, CORBA-IIOP)

  20. SOAP Overview, cont. • SOAP is typically transported from one computer to another as the payload of some other network protocol, usually the HyperText Transfer Protocol (HTTP) • Embedding SOAP in HTTP allows SOAP to freely pass through corporate firewalls (HTTP tunneling) • The primary use of SOAP is application-to-application (A2A) communication, specifically business-to-business (B2B) and enterprise application integration (EAI) • B2B is electronic commerce between businesses, as opposed to electronic commerce between a business and a consumer (B2C). EAI is the use of software called middleware to integrate the applications, databases, and legacy systems that support an organization’s critical business processes

  21. SOAP Overview, cont. B2B using SOAP over HTTP

  22. SOAP Overview, cont. EAI using SOAP over HTTP

  23. SOAP Overview, cont. • The SOAP specification is maintained by the World Wide Web Consortium (W3C) – http://www.w3c.org • The current versions of SOAP are 1.1 and 1.2 • SOAP has enjoyed widespread acceptance by the software community and is endorsed by most enterprise software vendors and standards organizations like W3C, the Organization for the Advancement of Structured Information Systems (OASIS), and the Web Services Interoperability Organization (WS-I) • Due to its platform-independence and vendor backing, SOAP has become the de facto communication protocol standard for invoking applications over a network

  24. SOAP Concepts • SOAP is a decentralized, stateless, one-way message exchange paradigm where XML messages are passed from an initiator, through zero or more intermediate locations, to a final destination • A SOAP message is the SOAP XML document instance that is exchanged between SOAP applications over a network • The peers exchanging the SOAP message are called SOAP nodes (SOAP nodes are also called SOAP applications). Within SOAP messages a SOAP node is identified by a URI. SOAP nodes handle routing and processing of the SOAP message and are categorized into one of three concepts - SOAP sender, SOAP receiver, and SOAP intermediary

  25. SOAP Concepts, cont. • SOAP sender: SOAP node that generates and transmits a SOAP message • SOAP receiver: SOAP node that receives and processes the SOAP message that was generated by a SOAP sender • SOAP intermediary: SOAP node that is considered a SOAP receiver as well as a SOAP sender. Zero or more intermediaries can lie between the initial SOAP sender and the ultimate SOAP receiver. These intermediaries can perform preprocessing of the message before it reaches its final destination. Common uses for intermediaries are security, logging, and transactions. • The set of SOAP nodes through which the SOAP message passes, including the initial sender and the ultimate receiver, are called the SOAP message path

  26. SOAP Concepts, cont. • The initial SOAP sender (also commonly called the SOAP client) is the SOAP sender that generated the original SOAP message • The ultimate SOAP receiver (also commonly called the SOAP server or Web service) is a SOAP receiver that is the final destination of a SOAP message SOAP Message Path

  27. SOAP Message Exchange Patterns • SOAP is defined as a one-way message transmission protocol, however real applications use various message exchange patterns (MEP) to communicate SOAP messages. • A familiar example of a MEP is that which occurs between a Web browser and a Web server when exchanging HTML embedding in an HTTP message HTTP Request-Response

  28. SOAP Message Exchange Patterns, cont. • The MEPs that can be used depend on what the underlying transport protocol supports. • SOAP was designed to be independent of the underlying protocol, so it only defines SOAP as one-way. • However, the SOAP designers fully expect SOAP messages to be combined in various exchange patterns, and therefore, they abstractly describe two MEPs in the SOAP specification: Request-Response and SOAP Response Request-Response MEP

  29. SOAP Message Exchange Patterns, cont. • Other forms of MEPs are One-Way, Notification, Single Request/Multiple Response, and Solicit-Response. • One-Way and Request-Response are the most popular MEPs in use today. Both are supported by HTTP, which is the most commonly used method for transporting SOAP messages. SOAP Response MEP

  30. SOAP Message Structure • A SOAP message is simply an XML document with it’s own XML schema, XML namespaces, and processing rules. • The XML document that defines a SOAP message is composed of the following four elements: • Envelope (mandatory) – Root of the XML document. • Header (optional) – An extension mechanism that can be used to pass application-specific information not contained in the message itself. • Body (mandatory) – Contains the application data that is being transported between applications. • Fault (optional) – Used to report errors back to a SOAP sender. Analogous to an Exception in Java.

  31. SOAP Message Structure, cont. • The SOAP Envelope is a package for data (a message) that is transported from a sender node to a receiver node. Structure of a SOAP Message with and without a Fault

  32. XML Namespaces in SOAP • XML namespaces are used in SOAP to eliminate ambiguity (prefixes help distinguish between elements or attributes with the same name), provide versioning and processing control, and support modularity. • The SOAP XML elements are defined in the SOAP XML schema. The namespace for the SOAP schema is: • (version 1.1) http://schemas.xmlsoap.org/soap/envelope • (version 1.2) http://www.w3.org/2003/05/soap-envelope • Different XML namespaces can be used for the different parts of the SOAP message (SOAP schema elements, header blocks, and XML in the Body), thus code that processes one part can change while the code that processes the other parts can remain the same (modularity).

  33. XML Namespaces in SOAP, cont. • The SOAP schema requires that local elements (including their attributes) be fully qualified via the use of prefixes or default namespaces. • Additionally the WS-I BP requires that all local elements within the SOAP Body be fully qualified as well. • The local elements of header blocks may be qualified or unqualified, although the best practice is to qualify them. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsu="…"> <soap:Body wsu:Id="Body"> <po:purchaseOrder xmlns:po="http://yourbusiness/PO"> … </po:purchaseOrder> </soap:Body> </soap:Envelope>

  34. SOAP Envelope Element • The root of the XML document that is a SOAP message, therefore all other SOAP elements are contained within the Envelope. • Mandatory and may contain a single, optional Header element followed by a single, mandatory Body element. • May also contain namespace declarations and attributes. If attributes are used in the Envelope, they must be namespace qualified. • Serves to tie together the application-specific data in the Body element with the header blocks in the Header element. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> … </soap:Envelope>

  35. SOAP Header Element • Optional, but if present it must be the immediate child of the Envelope element and precede the Body element. • May contain zero or more optional child elements, which are called header blocks. <soap:Envelope xmlns:soap="…"> <soap:Header> <trns:transactions xmlns:trns="…" soap:role="…"> <trns:transaction> <trns:id>http://bank/account1/withdraw</trns:id> <trns:status>ACTIVE</trns:status> </trns:transaction> </trns:transactions> </soap:Header> <soap:Body>…</soap:Body> </soap:Envelope>

  36. SOAP Header Element, cont. • A mechanism to include any information in the SOAP message that lies outside the semantics of the Body, but may be useful or even necessary to process the message appropriately. • A powerful extension mechanism, which allows you to add features and define high-level functionality such as security, transactions, and auditing. • Using header blocks to add functionality to SOAP messages is referred to as vertical extensibility. • An advantage of header blocks is that they add information to the SOAP message without altering the original application-specific XML contained in the Body.

  37. SOAP Header Element, cont. • The word process in the SOAP specification means to fulfill the contract indicated by a particular piece of a SOAP message (a header block or the application-specific XML in the Body). • Each SOAP header block may be intercepted and processed by any number of SOAP intermediaries along the message path. • When processing a header block, each SOAP intermediary reads, acts on, and removes the specific header block that it has been tagged to process from the SOAP message before sending the message on to the next SOAP node. • Additionally, each SOAP node may optionally add a header block to the SOAP Header element of the message (could even be the one it just processed).

  38. SOAP role Attribute • Optional. Used to identify the nodes that must process a specific header block. The node is identified by a URI. The URI might refer to a single node or a whole class of nodes. • Conceptually, it identifies a function to be performed by a particular node, in other words it identifies a role that the node must play in the SOAP message path. • When a node receives a SOAP message, it examines the Header element to determine which header blocks have specified a role that is supported by that node. A node may support multiple roles and therefore use several code modules to process multiple header blocks.

  39. SOAP role Attribute, cont. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Header> <sec:authenticate xmlns:sec=”http://security.example/version1” soap:role=”http://security.example/authenticator”> <sec:username>brighton</sec:username> <sec:key>w1cJdTvtONxK2NTwV+uwu34ahx8=</sec:key> </sec:authenticate> <log:audit xmlns:log=”http://auditing.example/version1” soap:role=”http://auditing.example/logger”/> </soap:Header> <soap:Body> … </soap:Body> </soap:Envelope>

  40. SOAP role Attribute, cont. • Even though a header block passes through one intermediary node without being processed, it may be processed by a node further down the message path. • http://www.w3.org/2003/05/soap-envelope/role/next - Standard role used to indicate that the next node in the message path must process this header block. • http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver - Standard role used to indicate that the ultimate receiver node should be the only node in the message path that processes the header block. • http://www.w3.org/2003/05/soap-envelope/role/none - Standard role used to indicate that none of the SOAP nodes along the message path should process this header block.

  41. SOAP role Attribute, cont. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Header> <sec:authenticate xmlns:sec=”http://security.example/version1” soap:role=”http://security.example/authenticator”> <sec:username>brighton</sec:username> <sec:key>w1cJdTvtONxK2NTwV+uwu34ahx8=</sec:key> </sec:authenticate> <trns:transactions xmlns:trns=”http://transaction.example/version1” soap:role=”http://www.w3.org/2003/05/soap-envelope/role/next”> </trns:transactions> </soap:Header> <soap:Body> … </soap:Body> </soap:Envelope>

  42. SOAP mustUnderstand Attribute • Optional. Used to indicate whether or not the processing of a header block by a targeted node is mandatory. • If a node doesn’t understand how to process one of the header blocks, then the node will look at the mustUnderstand attribute to determine if it can ignore the header block and pass it on. • A mustUnderstand value of “1” or “true”indicates the SOAP node must know how to process the header block (called mandatory header blocks). A value of “0” or “false” (the default) means it can be ignored. • SOAP nodes must generate a SOAP Fault for mandatory header blocks they don’t “understand” and must not forward the message on to the next node. If involved in a request-response exchange, the node must also send the Fault as a response back to the SOAP sender.

  43. SOAP mustUnderstand Attribute, cont. <soap:Envelope xmlns:soap=”http://www.w3.org/2003/05/soap-envelope”> <soap:Header> <trns:transactions xmlns:trns=”http://transaction.example/version1” soap:role=”http://www.w3.org/2003/05/soap-envelope/role/next” soap:mustUnderstand=”1”> </trns:transactions> </soap:Header> <soap:Body> … </soap:Body> </soap:Envelope>

  44. SOAP relay Attribute • Optional. Used to indicate whether or not a node should pass on a targeted header block that it does not understand. • Allows the code for some nodes in the same role and the same message path to be upgraded while the others remain the same. • A value of “1” or “true”, indicates that the node must forward the header block on the next node if it does not understand it. Value of “0” or “false” means it doesn’t. • The relay attribute has no effect when the mustUnderstand attribute is set to true because the relay attribute is for describing what should happen when a node doesn’t have to understand a targeted header block.

  45. SOAP relay Attribute, cont. <soap:Envelope xmlns:soap=”http://www.w3.org/2003/05/soap-envelope”> <soap:Header> <log:audit xmlns:log=”http://auditing.example/version1” soap:role=”http://www.w3.org/2003/05/soap-envelope/role/next” soap:relay=”1”/> </soap:Header> <soap:Body> … </soap:Body> </soap:Envelope>

  46. SOAP Intermediaries • Provide a mechanism for allowing distributed systems to easily scale in response to changes, and to provide value-added services along the message path (like security, transactions, routing, and message persistence). • Provide another mechanism for extending SOAP that is referred to as horizontal extensibility. You can add more intermediaries to the message path and extend the message path “horizontally”, thereby adding functionality. • Forwarding Intermediaries – do processing that is defined by the contents of the inbound message but do not modify the message, and then forward the message on to another node in the message path. • Active Intermediaries – modifies the SOAP message in ways that are not described by the contents (header blocks) of the inbound message.

  47. SOAP Body Element • Mandatory, and must be the first child element of the Envelope element, unless a Header element is present, in which case the Body element must follow the Header element. • May contain either application-specific XML or a Fault element, but not both. • The Body element is just a wrapper for the XML document that we want to exchange. The Fault element is used only when an error occurs. • The ultimate SOAP receiver must be able to process the application-specific XML of the Body, otherwise it should generate a SOAP Fault. • Unlike header blocks, the Body contents are intended only for the ultimate receiver, and thus should not be modified by intermediaries (but can be read by intermediaries).

  48. SOAP Body Element, cont. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Body> <shp:trackingRequest xmlns:shp=”http://kellys-fast-shipping.co”> <shp:trackingNum>1Z 999 999 99 9999 999 9 </shp:trackingNum> </shp:trackingRequest> </soap:Body> </soap:Envelope>

  49. SOAP Fault Element • A standard mechanism for handling errors. Analogous to the java.lang.Exception. • Receivers generate a Fault element when an error occurs, place it inside the Body element, and send the SOAP message back to the previous sender in the path. • A receiver is only required to send a Fault upstream to a sender if the MEP being used is Request/Response. If a one-way MEP is being used, then the receiver must generate a Fault, but is not required to attempt to send the Fault to the sender. • When the Fault element is used, the Body element must contain only the Fault as a single child element and no others. The presence of the Fault element indicates to a SOAP node that an error has occurred. A SOAP message containing a Fault element is called a fault message.

  50. SOAP Fault Element, cont. • The Fault element may contain the following elements to describe what the error was: • Code (mandatory) – Used to classify the SOAP Fault. • Reason (mandatory) – Contains one or more human-readable explanations of the Fault. • Node (optional) – Used to provide information about which SOAP node on the message path generated the Fault. • Role (optional) – Used to identify the role the node was acting in when it generated the Fault. • Detail (optional) – Used to carry additional application-specific information (typically machine-readable) about the error, which is related to the fault code.

More Related