Introduction to Java Enterprise Edition For Database Application Developer

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

Developing Applications with Java EE 6 on WebLogic Server 12c

Java EE 7: Back-End Server Application Development

Java Enterprise Edition

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

CO Java EE 7: Back-End Server Application Development

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

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

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

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

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Fast Track to EJB 3.0 and the JPA Using JBoss

CO Java EE 6: Develop Database Applications with JPA

Module 8 The Java Persistence API

Deccansoft Software Services. J2EE Syllabus

Enterprise JavaBeans, Version 3 (EJB3) Programming

Java SE7 Fundamentals

<Insert Picture Here> Productive JavaEE 5.0 Development

Oracle 10g: Build J2EE Applications

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

Java SE 8 Fundamentals

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

Java EE 6: Develop Business Components with JMS & EJBs

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

Courses For Event Java Advanced Summer Training 2018

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

Thu 10/26/2017. Created RESTful Web Service, JavaDB, Java Persistence API, Glassfish server in NetBeans 8

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

Shale and the Java Persistence Architecture. Craig McClanahan Gary Van Matre. ApacheCon US 2006 Austin, TX

JPA The New Enterprise Persistence Standard

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

Chapter 6 Enterprise Java Beans

Migrating traditional Java EE applications to mobile

open source community experience distilled

presentation DAD Distributed Applications Development Cristian Toma

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

Introduction to JPA. Fabio Falcinelli

Enterprise Java Unit 1-Chapter 2 Prof. Sujata Rizal Java EE 6 Architecture, Server and Containers

Deployment. See Packaging and deployment processes

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

1Z Oracle. Java Enterprise Edition 5 Enterprise Architect Certified Master

Lightweight J2EE Framework

Topics in Enterprise Information Management

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

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

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8

JVA-163. Enterprise JavaBeans

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

Exam Questions 1Z0-895

"Web Age Speaks!" Webinar Series

Table of Contents EJB 3.1 and JPA 2

Fast Track to Java EE

object/relational persistence What is persistence? 5

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

Course Content for Java J2EE

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

Session 13. Reading. A/SettingUpJPA.htm JPA Best Practices

5/2/2017. The entity manager. The entity manager. Entities lifecycle and manipulation

Java Persistence API (JPA) Entities

Appendix A - Glossary(of OO software term s)

INTRODUCTION TO COMPONENT DESIGN IN JAVA EE COMPONENT VS. OBJECT, JAVA EE JAVA EE DEMO. Tomas Cerny, Software Engineering, FEE, CTU in Prague,

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

Java EE 6: Develop Web Applications with JSF

Web Application Development Using Spring, Hibernate and JPA

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

WHAT IS EJB. Security. life cycle management.

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

J2EE Interview Questions

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

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Distributed Multitiered Application

The Good, the Bad and the Ugly

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

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

Data Management in Application Servers. Dean Jacobs BEA Systems

1Z Java SE 5 and 6, Certified Associate Exam Summary Syllabus Questions

Contents at a Glance

Java J Course Outline

Page 1

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

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

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

Web Application Development Using Spring, Hibernate and JPA

1 Markus Eisele, Insurance - Strategic IT-Architecture

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

DESIGN PATTERN - INTERVIEW QUESTIONS

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

Hibernate Overview. By Khader Shaik

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

New Features in EJB 3.1

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.

Java Persistence API (JPA)

/ / JAVA TRAINING

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13

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

Building the Enterprise

WA1278 Introduction to Java Using Eclipse

Web Application Development Using Spring, Hibernate and JPA

Application Servers in E-Commerce Applications

Transcription:

CMP 420/758 Introduction to Java Enterprise Edition For Database Application Developer Department of Mathematics and Computer Science Lehman College, the CUNY 1 Java Enterprise Edition Developers today increasingly recognize the need for distributed, transactional, and portable applications that leverage the speed, security, and reliability of server-side technology. Enterprise applications provide the business logic for an enterprise. They are centrally managed and often interact with other enterprise software. In the world of information technology, enterprise applications must be designed, built, and produced for less money, with greater speed, and with fewer resources. The aim of the Java EE platform is to provide developers with a powerful set of APIs while shortening development time, reducing application complexity, and improving application performance. 2 1

Java Enterprise Edition (cont d) The Java Platform, Enterprise Edition (Java EE) builds upon the Java SE platform and provides a set of technologies for developing and running portable, robust, scalable, reliable and secure server-side applications. EE technologies are loosely divided into two categories: Web application technologies Enterprise application technologies Depending on your needs, you may want to use certain technologies from either category. For example, makes use of Servlet, JSP/EL, and JSTL "web" technologies (or JSF), as well as EJB and JPA "enterprise" technologies. 3 Java Enterprise Edition (cont d) 4 2

Java EE Components Applets: GUI app s executed in a web browser. They use the Swing API to provide powerful user interfaces. Applications: programs executed on a client. Typically GUIs or batchprocessing programs that have access to all the facilities of the Java EE middle tier. Web applications: applications executed in a web container and respond to HTTP requests from web clients. Made of servlets, servlet filters, JSP pages, and JSF. Servlets also support web service endpoints Enterprise Java Beans: container-managed components for processing transactional business logic. They can be accessed locally and remotely through RMI (or HTTP for SOAP and RESTful web services). 5 Java EE Application In a Java EE application: The model -- business layer functionality represented by JavaBeans or EJBs The view -- the presentation layer functionality represented by JSPs or JSFs in a web application The controller -- Servlet mediating between model and view Must accommodate input from various clients including HTTP requests from web clients, and WML from wireless clients XML documents from suppliers JSON messages, etc. MVC Architecture (or termed Design Pattern) 6 3

MVC Architecture Model: Represents the business data and any business logic that govern access to and modification of the data. The model notifies views when it changes and lets the view query the model about its state. It also lets the controller access application functionality encapsulated by the model. View: The view renders the contents of a model. It gets data from the model and specifies how that data should be presented. It updates data presentation when the model changes. A view also forwards user input to a controller. Controller: The controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. In a web application, user inputs are HTTP GET and POST requests. A controller selects the next view to display based on the user interactions and the outcome of the model operations. Source: Java BluePrints - J2EE Patterns, MVC http://java.sun.com/blueprints/patterns/mvc-detailed.html 7 MVC Architecture (cont d) 8 4

MVC- an example (based on JDBC) 9 MVC- an example (based on JPA) 10 5

MVC- an example (Spring framework) 11 JSF Flow of Control balance.xhtml Uses <h:commandbutton action="#{bankform.findbalance}"/> and <h:inputtext value="#{bankform.customerid}"/> When form submitted, textfield value passed to setcustomerid. When form first displayed, getcustomerid is called. If it is non-empty, it becomes initial value of the textfield. submit form POST request balance.jsf Run Setter Methods Find Bean If bean is request-scoped, instantiate it. But for other scopes (e.g., session), you might use existing bean instance. Business Logic results Run Action Controller Method return value The results get stored in the placeholder. E.g., a Customer that corresponds to the customer ID is found and placed in an instance variable of main bean. Choose Page This is the method listed in the action of h:commandbutton (e.g., findbalance) forward result1.xhtml result2.xhtml... resultn.xhtml Uses #{bankform.someproperty} to display bean properties 12 This could be #{bankform.customerid}, where customerid was passed in by the user, or it could be #{bankform.customer.balance}, where getcustomer returns the Customer object found by the business logic, and getbalance returns that customer s bank account balance. 6

Web Application A web application is a dynamic extension of a web or application server. Types of web applications: Presentation-oriented generates interactive web pages containing various types of markup language (HTML, XHTML, XML, and so on) and dynamic content in response to requests. Service-oriented A service-oriented web application implements the endpoint of a web service. In Java EE platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, web pages, web service endpoints, JSP pages, or JSFs 13 View layer in Web Application Display information according to client types Display result of business logic (Model) Not concerned with how the information was obtained, or from where (since that is the responsibility of Model) 14 7

Model layer in Web Application Models the data and behavior behind the business process What it s responsible for: Performing DB queries Calculating the business process Processing orders Encapsulation of data and behavior which are independent of presentation 15 Controller in Web Application Serves as the logical connection between the user's interaction and the business services on the back end servers Responsible for making decisions among multiple presentations e.g. User's language, locale or access level dictates a different presentation. A request enters the application through the control layer, which will decide how the request should be handled and what information should be returned 16 8

Containers Java EE is a set of specifications implemented by different containers. Containers are Java EE runtime environments that provide certain services to the components they host such as lifecycle management, dependency injection, security, etc. 17 GlassFish AS Container 18 9

JSP, Servlets, and JSF JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. Servlets are Java classes that dynamically process requestsand construct responses. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling non-textual data. JavaServer Faces (JSF) and Facelets are used for building interactive web applications. Java Server Faces and Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are generally used for presentation oriented applications. 19 JAVA EE Services and APIs JPA: Standard API for object-relational mapping (ORM). JMS: allows components to communicate asynchronously through messages. Queue (producer/consumer) Topic (publisgher/subscriber) Java Naming and Directory Interface (JNDI): used to access naming and directory systems. JTA: a transaction API JAX-WS (SOAP based), JAX-RS (RESTful HTTP based) 20 10

JPA Objects vs. Entities Objects are instances that just live in memory. Entities are objects that live shortly in memory and persistently in a database. JPA maps objects to a database via metadata that can be supplied using annotations or in an XML descriptor Annotations: The code of the entity is directly annotated with all sorts of annotations described in the javax.persistence package. Entity example in the next page 21 @Entity @Table(name = "category") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"), @NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"), @NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")}) public class Category implements Serializable { private static final long serialversionuid = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Short id; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "name") private String name; @OneToMany(cascade = CascadeType.ALL, mappedby = "categoryid") private Collection<Product> productcollection; public Category() { } public Category(Short id) { this.id = id; } 22 11

JPA cont d Relational model (i.e. RDBMS) vs. Object Oriented model (i.e. Java) Object-Relational Mapping (ORM) Java Persistence API (JPA) An API on top of JDBC Can access and manipulate relational data from Enterprise Java Beans (EJBs), web components, and Java SE applications Includes an entity manager API to perform DB-related operations like CRUD Includes JPQL, an object-oriented query language 23 EJB Server-side components Encapsulate business logic Take care of transactions and security Used in building business layers to sit on top of the persistence layer and as an entry point for presentation-tier technologies such as JSP, JSF Can be built by annotating a POJO that will be deployed into a container 24 12

Type of EJBs Session beans and Message-driven Beans (MDBs) Session Beans are used to encapsulate high-level business logic and can be Stateful: the state of the bean is maintained across multiple method calls. The "state" refers to the values of its instance variables. Because the client interacts with the bean, this state is often called the conversational state. Stateful session bean contains conversational state, which must be retained across method invocations for a single user Stateless: contains no conversational state between invocations, and any instance can be used for any client Singleton: A single session bean is shared between clients and supports concurrent access 25 More about JPA/JTA and EJBs 26 13

Why EJB and JPA? (1) Most server-side applications have a lot in common including business logic implemented managing application state storing and retrieving information/data from/to a relational database managing transactions implementing security performing asynchronous processing (mainly performing messaging applications) integrating systems, etc. 27 Why EJB and JPA? (2) Web application built based on JSP(EL/JSTL) and Sevlet technologies (or Java Server Faces) with database access (using JDBC/JNDI) can be run in any web server such as Glassfish Server and WebSphere. You can continue develop web application using these technologies for small and medium sized applications. Your application may need to have additional functionality such as thread-safety, transactions, and security (although such functionality may be provided by the backend DBMS). 28 14

Why EJB and JPA? (3) Data should be managed transparently The user interface should not perform business logic Especially when there are multiple interfaces (web, mobile, desktop) The business layer implement business logic should be separated from the data managing layer Should be separated from presentation layer add transaction management and security 29 Why EJB and JPA? (4) EJB technology is a server-side component architecture that enables rapid and simplified development of distributed, transactional, secure, and portable applications the services provided by the technology remain transparent to the developer Eliminating the tedious and often error-prone task of adding a lot of boiler plate code which would otherwise be required 30 15

MVC Architecture MVC (Model View Controller) Architecture the model, business logic, and presentation layers The model is encapsulated by entities Keep the entities as transparent as possible, free of business logic They can have methods to validate their attributes The business logic is encapsulated by EJBs... Model the actions of the application (reserve a seat, buy a ticket, etc) The presentation layer Can be built with different technologies, depending on the target audience (web users? mobile devices? desktop apps?) By implementing the business logic in EJBs, it can be used by other apps 31 EJB Containers EJB container runtime environment that provides services, such as transaction management, concurrency control, pooling, and security authorization. Historically, application servers have added other features such as clustering, load balancing, and failover. Using Enterprise beans with JPA entity classes allows you focus on the business logic of your application while relying on solutions that have already been tried and tested. Some JEE Application Servers GlassFish (Sun/Oracle, open source edition) WebSphere (IBM) WebLogic (Oracle) JBoss (RedHat) WebObjects (Apple) 32 16

EJB Services (1) You can think of EJB both as components, or Java classes that are incorporated in your project, as well as a framework that provides numerous enterprise-related services. Pooling: For each EJB component, the EJB platform creates a pool of component instances that are shared by clients. At any point in time, each pooled instance is only allowed to be used by a single client. As soon as an instance is finished servicing a client, it is returned to the pool for reuse instead of being discarded for the garbage collector to reclaim. Thread Safety: EJB makes all components thread-safe in ways that are completely invisible. This means that you can write your server components as if you were developing a single-threaded desktop application. It doesn't matter how complex the component itself is 33 EJB Services (2) Transactions: EJB supports declarative transaction management that helps you add transactional behavior to components using simple configuration instead of coding. You can designate any component method to be transactional. If the method completes normally, EJB commits the transaction and makes the data changes made by the method permanent. Otherwise the transaction is rolled back. Security: EJB supports integration with the Java Authentication and Authorization Service (JAAS) API It is easy to secure an application using simple configuration instead of writing security code. 34 17

JPA (Java Persistence API) 35 Java Persistence In the context of Java Enterprise, persistence refers to the act of automatically storing data contained in Java objects into a relational database. The Java Persistence API (JPA) is an object-relational mapping (ORM) technology that enables applications to manage data between Java objects and a relational database in a way that is transparent to the developer. This means that you can apply JPA to your projects by creating and configuring a set of Java classes (entities) that mirror your data model. Your application can then access these entities as though it were directly accessing the database. ORM Tools Programmers can create their own using JDBC Hibernate, ibatis, JDO ADO.NET Entity Framework (Microsoft) EclipseLink, etc 36 18

Benefits to using JPA POJO persistence ORM is completely metadata-driven No complex data access objects (DAO). The API helps you manage transactions. Write standards-based code that interacts with any relational database, freeing you from vendor-specific code. JPA has its own rich, SQL-like query language for static and dynamic queries. Using the Java Persistence Query Language (JPQL), your applications remain portable across different database vendors. You can avoid the task of writing low-level, verbose JDBC/SQL code. JPA transparently provides services for data caching and performance optimization. You can also use the Java Persistence API for desktop application persistence -- not just for enterprise apps. 37 JPA Concepts (1) JPA maps objects to a database through metadata. Associated with every entity is metadata that describes the mapping. Metadata can be written in two different formats: Annotations: The code of the entity is directly annotated with all sorts of annotations described in the javax.persistence package. XML descriptors: The mapping is defined in an external XML file that will be deployed with the entities. Can be used instead of (or in addition to) annotations Better portability and maintenance in some cases 38 19

JPA Concepts (2) Entity: an application-defined object with the following characteristics it can be made persistent it has a persistent identity (i.e. a key) it s partially transactional... that is: an entity is created, updated and deleted within a transaction. However, in-memory entities can be changed without the changes being persisted it s not a primitive, a primitive wrapper, or built-in object Entity metadata: describes every entity Entity manager: enables API calls to perform operations on an entity Until an entity manager is used to create, read, or write an entity the entity is just a regular non-persistent Java object. 39 JPA Concepts (3) The Entity-Relationship Model has been around since 1975 by Peter Chen. Entities are the objects or things in the model Relationships are the connections or links between entities JPA requires that you identify the classes of those objects that you will store in a database. Use the annotation @Entity to define classes that it will map to a relational database. Relationships have cardinality constraints Use the annotations @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships among entities. 40 20

Entity Class Entity classes make up the model in the MVC design pattern. Essentially an entity is a plain old Java object (POJO) that holds data for the purposes of saving that data in a database. An entity class has the following characteristics: The class is annotated with the @Entity annotation so that the Enterprise container will recognize it as an entity class. The class's member variables should not be public. Access to the variables should be through accessor (getter) and mutator (setter) methods. The class should have a no-argument constructor. It may have other constructors, but the no-argument constructor must exist. The member variables that will be persisted to a database can be primitive types, serializable classe types, or Multi value types (Collections, Maps and Arrays). 41 GuestBook.java Entity Class (1) @Entity @Table(name = "guestbook") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Guestbook.findAll", query = "SELECT g FROM Guestbook g"), @NamedQuery(name = "Guestbook.findById", query = "SELECT g FROM Guestbook g WHERE g.id = :id"), @NamedQuery(name = "Guestbook.findByFirstname", query = "SELECT g FROM Guestbook g WHERE g.firstname = :firstname"), @NamedQuery(name = "Guestbook.findByLastname", query = "SELECT g FROM Guestbook g WHERE g.lastname = :lastname")}) public class Guestbook implements Serializable { private static final long serialversionuid = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "ID") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "FIRSTNAME") private String firstname; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name 42 = "LASTNAME") private String lastname; 21

GuestBook.java Entity Class (2) public Guestbook() { } public Guestbook(Integer id) { this.id = id; } public Guestbook(Integer id, String firstname, String lastname) { this.id = id; this.firstname = firstname; this.lastname = lastname; } public Integer getid() { return id; } public void setid(integer id) { this.id = id; } public String getfirstname() { return firstname; } public void setfirstname(string firstname) { this.firstname = firstname; } 43 GuestBook.java Entity Class (3) public String getlastname() { return lastname; } public void setlastname(string lastname) { this.lastname = lastname; } @Override public int hashcode() { int hash = 0; hash += (id!= null? id.hashcode() : 0); return hash; } @Override public boolean equals(object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Guestbook)) { return false; } Guestbook other = (Guestbook) object; if ((this.id == null && other.id!= null) (this.id!= null &&!this.id.equals(other.id))) { return false; } return true; } @Override 44 public String tostring() { return "entity.guestbook[ id=" + id + " ]"; 22

Annotations (1) An entity class is a simple POJO class decorated with some annotations. These annotations are essential for the object-relational mapping work. Entity classes should have the @Entity annotation applied so that Java can tell that it is supposed to be an entity class instead of a simple non-persistent class. The id member variable has two annotations, @Id and @GeneratedValue. Each entity must have an @Id annotation. This tells JPA that the data element is the primary key in the database. Without a primary key JPA would have no way to distinguish one record from another in the database. The @GeneratedValue annotation is optional 45 Annotations (2) The firstname instance variable is annotated with @Column. This is an optional annotation that tells JPA that the database column name for this variable is firstname. If this annotation was not present JPA would look for a column with the same name as the variable. Because the id has no @Column annotation JPA will look for a column named id to store the content of the id. An entity class may use either persistent fields or persistent properties depending on where the annotations are placed. If the annotations are applied to the member variables then the entity will use persistent fields. If persistent properties are used, then the member variable's accessor (getter) method would be annotated. Do not mix two different annotations Using persistent fields is preferred 46 23

Annotations (3) A primary key in a database table does not need to be a single column. Likewise an entity's Id doesn't have to be a single variable. Simple PK Use @Id annotation on an attribute, can be one of the typical scalar data types (including String, Date, Integer) Use @GeneratedValue to have the value of the PK be generated automatically by the persistence provider Composite PK -- two ways to annotate it @EmbeddedId (recommended): create a Java class for the PK annotated with @Embeddable and then create a field of this type in the Entity annotated with @EmbeddedId Embeddable objects do not have a persistent identity on their own; they can be embedded only within owning entities. @IdClass: create a Java class for the PK w/no annotations, then annotate the entity with @IdClass Both approaches get mapped to the same table structure 47 @Column Annotation Some important defaults: name of column is the same as that of the field null values allowed on non-primitive data types Strings have a length of 255 Sample use... @Column(name="firstName") @Column(name= firstname", unique=false, length=100) 48 24

Other annotations @Transient To annotate a field that is not to be persisted @Access To annotate whether FIELD or PROPERTY access type is to be used. Avoid using this annotation if it s not necessary. @ElementCollection and @CollectionTable For annotating a field that is a Collection Java types In the DB, a table will be created for the values in the collection 49 Storing and Manipulating Entities 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. The EntityManager is the means by which an application accesses the persistence context. Unlike session beans, entities are not directly managed by the enterprise container. They are managed by the persistence context (which does not require an enterprise container). Example In the Java SE environment, the application manages the life cycle of an entity manager -- there is no container Creating an entity manager in Java SE EntityManagerFactory emf = Persistence.createEntityManagerFactory( AffablebeanPU"); EntityManager em = emf.createentitymanager(); Start a transaction from which to modify data em.gettransaction().begin(); A transaction is not needed if you just query to retrieve data 50 25

Entity Life Cycle (1) may be revised When you create a new instance of an entity class you have an entity in the new state. An entity object becomes Managed when it is persisted to the database via an EntityManager s persist method, which must be invoked within an active transaction. On transaction commit, the owning EntityManager stores the new entity object to the database. 51 Entity Life Cycle (2) Entity objects retrieved from the database by an EntityManager are also in the Managed state.. If a managed entity object is modified within an active transaction the change is detected by the owning EntityManager and the update is propagated to the database on transaction commit. A managed entity object can also be retrieved from the database and marked for deletion, by using the EntityManager s remove method within an active transaction. The entity object changes its state from Managed to Removed, and is physically deleted from the database during commit. The last state, Detached, represents entity objects that have been disconnected from the EntityManager. All the managed objects of an EntityManager become detached when the EntityManager is closed. Working with detached objects, including merging them back to an EntityManager is possible. 52 26

Persistence Context The persistence context is the collection of all the managed objects of an EntityManager. If an entity object that has to be retrieved already exists in the persistence context, the existing managed entity object is returned without actually accessing the database (except retrieval by refresh, which always requires accessing the database). The main role of the persistence context is to make sure that a database entity object is represented by no more than one inmemory entity object within the same EntityManager. Every EntityManager manages its own persistence context. Therefore, a database object can be represented by different memory entity objects in different EntityManager instances. Retrieving the same database object more than once using the same EntityManager should always result in the same in-memory entity object. 53 EntityManager API persist: make an instance managed and persistent find: search for an entity of a specified class and PK value getreference: like find but with lazy fetch remove: remove the entity from the persistence context and from the DB flush: forces any changes to be flushed to the database, otherwise they will be done at commit time of the transaction -- changes can still be rolled back. refresh: overwrites the current state of a managed entity with data that is in the DB merge, createquery, createnamedquery 54 27

Querying via JPQL The results obtained from SQL are in the form of rows and columns (tables), whereas JPQL uses an entity or a collection of entities. JPQL syntax is object-oriented JPQL is mapped to SQL and JDBC calls Done automagically! 55 JPQL Example @NamedQuery(name = "Guestbook.findAll", query = "SELECT g FROM Guestbook g") Or You can write a statement to create JPQL //em EntityManager object List<Guestbook> guestlist = em.createquery("select g FROM Guestbook g").getresultlist(); 56 28

EJB (Enterprise Java Beans) 57 Types of EJBs SessionBean: EJB used for implementing high-level business logic and processes Session beans handle complex tasks that require interaction with other components (servlet controllers, entities, web services, messaging, etc.) Timer Service EJB used for scheduling tasks Message Driven Bean EJB used to integrate with external services via asynchronous messages using JMS. Usually, delegate business logic to session beans 58 29

Session Beans Enterprise session beans are invoked by a client in order to perform a specific business operation. The name session implies that a bean instance is available for the duration of a "unit of work". The EJB 3.1(3.2) specification describes a typical session object as having the following characteristics: Executes on behalf of a single client Can be transaction-aware Updates shared data in an underlying database Does not represent directly shared data in the database, although it may access and update such data Is relatively short-lived Is removed when the EJB container crashes. The client has to reestablish a new session object to continue computation. 59 Types of Session Beans EJB provides three types of session beans: stateful, stateless, and singleton. Stateless: Stateless beans are used for operations that can occur in a single method call. When the method finishes processing, the client-specific state of the bean is not retained. A stateless session bean therefore does not maintain a conversational state with the client. Stateful: The state of the bean is maintained across multiple method calls. Useful for tasks that have to be done in several steps. The "state" refers to the values of its instance variables. Because the client interacts with the bean, this state is often called the conversational state. Singleton: A singleton session bean is instantiated once per application, and exists for the lifecycle of the application. Singleton session beans are designed for circumstances where a single enterprise bean instance is shared across and concurrently accessed by clients. 60 30