Writing Enterprise Applications with J2EE (Seventh lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialistica in Informatica – Università di Trento.
Advertisements

12 Copyright © 2005, Oracle. All rights reserved. Implementing Business Tasks with Session EJBs.
Technische universität dortmund Service Computing Service Computing Prof. Dr. Ramin Yahyapour IT & Medien Centrum 12. November 2009.
EJB Entity Beans. Entity Beans Data versus logic Used to represent an instance rather than a collection of data (depending on underlying storage) Represents.
Development and Deployment Roles Venugopal Pakanati.
Container Managed Persistence. General Guidelines Home and Remote interfaces are implemented the same as for bean managed persistence Entity Bean class.
Writing Enterprise Applications with J2EE (Sixth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
Writing Enterprise Applications with J2EE (First lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
Writing Enterprise Applications with J2EE (Third lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
Writing Enterprise Applications with J2EE (Fifth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
Emmanuel Cecchet et al.  Performance Scalability of J2EE application servers.  Test effect of: ◦ Application Implementation Methods ◦ Container Design.
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
Database Programming in Java Corresponds with Chapter 32, 33.
EJB. Component Characteristics An enterprise Bean typically contains business logic that operates on the enterprise’s data. An enterprise Bean’s instances.
4-Tier Model Client Tier Web Tier Business Tier EIS Tier.
Brad Rippe Fullerton College. What you need to get started? JDK 1.3 standard for compilation J2EE - SDK1.2.1 App Server - An EJB Container/Web Container.
1 Session Bean Chuyên đề Lập trình Java & J2EE Chương 14 Biên soạn: Th.S Nguyễn văn Lành.
J2EE Part 2: Enterprise JavaBeans CSCI 4300 Images and code samples from jGuru EJB tutorial,
Enterprise Java Beans - (EJB)
Writing Enterprise Applications with J2EE (Second lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
Distributed Object-Oriented Programming (3) – Enterprise JavaBeans SNU iDB Lab. Taewhi Lee May 14th, 2007.
Entity Beans BMP Celsina Bignoli
Middleware Technology (J2EE/EJB) Entity Bean. 2 Introduction to Entity Beans Persistence Concepts Entity beans are persistent objects that can be stored.
Lecture 8 Advanced Topics in Enterprise JavaBeans.
Objektorienteret netværkskommuniation(ITONK1) Persistence.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Advanced Java Session 7 New York University School of Continuing and Professional Studies.
Container-Managed Persistence (CMP) Entity Beans Lesson 3A / Slide 1 of 42J2EE Server Components Objectives In this lesson, you will learn to: Identify.
Distributed Systems 1 Master of Information System Management Distributed Systems Persistence.
The Triad of Beans I Oleh: Dini Addiati ( ) Fahrurrozi Rahman ( Y) Irfan Hilmy ( ) Salman Azis A ( ) Aziiz Surahman.
Enterprise JavaBeans. Lesson 1: Introduction to Server-Side Component Software.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Enterprise Java Bean Computer Networks Natawut Nupairoj, Ph.D. Department of Computer Engineering Chulalongkorn University.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
Session Beans -) stateless -) stateful. Session Beans A session bean represents a single client inside the J2EE server. To access an application that.
Writing Enterprise Applications with J2EE (Fourth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
© jGuru.com Enterprise JavaBeans Fundamentals.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
EXAMPLE I An application showing JDBC access to Cloudscape.
EJB Overview: Constraint Types and Enforcement in JBoss Elissa Newman Fluid Meeting 6/3/04.
Entity Beans & Persistence Chris Alexander CS 486 Spring 2001.
Session Beans Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Enterprise Java Beans N.V.RAJASEKHAR REDDY. Definition of EJB EJBs are the components that are the set of classes and interfaces deployed within a container.
Copyright © 2002 ProsoftTraining. All rights reserved. Enterprise JavaBeans.
Enterprise Java Beans Ye Zhou CS6704 Presentation Virginia Tech.
13 Copyright © 2004, Oracle. All rights reserved. Managing Persistent Data in the Business Tier Entity EJBs.
D Copyright © 2004, Oracle. All rights reserved. BMP Entity EJBs J2EE Connector Architecture.
Enterprise JavaBeans. Lesson 1: Introduction to Server-Side Component Software.
Advanced Java Session 7 New York University School of Continuing and Professional Studies.
Enterprise JavaBeans™ Trademark of Sun Microsystems, Inc.
Session Beans & Business Logic CS 486 Sagar Deshpande.
14 Copyright © 2004, Oracle. All rights reserved. Achieving State Management in the Business Tier.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JAVA & J2EE UNIT – 8 ENTERPRISE JAVA BEAN - EJB 28-Jun-16 Prepared by: SANTHIYA.M & GANGA V. C. Department: Computer Science & Engineering Course code:
©NIIT Session Beans Lesson 1B/ Slide 1 of 37J2EE Server Components Objectives In this lesson, you will learn to: Describe the characteristics of session.
JDBC 15-Apr-18.
Entity Bean Chuyên đề Lập trình Java & J2EE Chương 15
“Controlling your application” (the business logic)
Structure of Enterprise Java Beans
JDBC 15-Nov-18.
Objectives In this lesson, you will learn to:
EJB Types Alessio Bechini June 2002.
Understanding and Designing with EJB
Entity Beans B.Ramamurthy 2/17/2019 BR.
Knowledge Byte In this section, you will learn about:
Understanding and Designing with EJB
Presentation transcript:

Writing Enterprise Applications with J2EE (Seventh lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)

Bean-Managed Persistence & JDBC In the examples up to this point, the container has been handling data storage and retrieval on behalf of the entity bean (Container-managed persistence). It’s possible to override the default container-managed persistence and implement bean-managed persistence: in this last case, entity or session bean methods are implemented to use SQL commands. Bean-managed persistence can be useful if you need to improve performance or map data in multiple beans to one row in a database table. This lesson changes the entity bean in the example application to use bean-managed persistence: follow these steps. Change the BonusBean Code Change the CalcBean and JBonusBean Code Create the Database Table Remove the JAR File Verify, Deploy, etc.

Bean Lifecycle Lifecicle methods: setEntityContext ejbCreate ejbPostCreate: unsetEntityContext ejbFindByPrimaryKey ejbLoad and ejbStore ejbActivate and ejbPassivate Does not exist Pool Ready unsetEntityContext ejbHome ejbFind ejbSelect ejbPassivate ejbRemove ejbSelect Any operating method ejbLoad ejbStore 1) Class.newInstance 2) setEntityContext 1) ejbCreate 2) EjbPostCreate or ejbActivate

Import Statements package Beans; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.naming.InitialContext; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.ejb.FinderException; import java.sql.SQLException;

Instance Variables The new added instance variables let us establish and close database connections. The string java:comp/env/jdbc/BonusDB indicates the resource reference name, which you also specify when you add the entity bean to the J2EE application using the Deploy tool. In this example, the resource reference is an alias to the Cloudscape database ( CloudscapeDB ) where the table data is stored. Later, we’ll create the BONUS table in the C loudscapeDB, and during deployment, we’ll map jdbc/BonusDB to jdbc/CloudscapeDB. public class BonusBean implements EntityBean { private EntityContext context; private Connection con; private String dbName ="java:comp/env/jdbc/BonusDB"; private InitialContext ic = null; private PreparedStatement ps = null; private double bonus; private String socsec;

Business Methods The business methods have not changed for this lesson except for calls to System.out.println, which let you see the order in which business and lifecycle methods are called at runtime. public double getBonus() { System.out.println("getBonus"); return this.bonus; } public String getSocSec() { System.out.println("getSocSec"); return this.socsec; }

LifeCycle Methods: ejbCreate The current ejbCreate method throws RemoteException and SQLException in addition to CreateException. SQLException is needed because the current ejbCreate method provides its own SQL code, and RemoteException is needed because this method performs remote access. One thing to notice about this class is that ejbCreate returns a String value (the primary key), but the declaration for this method in the home interface expects to receive a Bonus class instance. The container uses the primary key returned by this method to create the Bonus instance. public interface BonusHome extends EJBHome { public Bonus create(double bonus, String socsec) throws CreateException, RemoteException; public Bonus findByPrimaryKey(String socsec) throws FinderException, RemoteException; }

ejbCreate: Code public String ejbCreate(double bonus, String socsec) throws RemoteException, CreateException, SQLException { this.socsec=socsec; this.bonus=bonus; System.out.println("Create Method"); try { //Establish database connection ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); //Use PreparedStatement to form SQL INSERT statement //to insert into BONUS table ps = con.prepareStatement("INSERT INTO BONUS VALUES (?, ?)"); //Set 1st PreparedStatement value marked by ?, with //socsec and the 2nd value marked by ?) with bonus ps.setString(1, socsec); ps.setDouble(2, bonus); ps.executeUpdate(); } catch (javax.naming.NamingException ex) { ex.printStackTrace(); } finally { //Close database connection ps.close(); con.close(); } //Return primary key return socsec; }

LifeCycle Methods: ejbPostCreate This method has the same signature as ejbCreate, but no implementation because this simple example performs no post create processing or initialization. public void ejbPostCreate(double bonus, String socsec) throws RemoteException, CreateException, SQLException { System.out.println("Post Create"); }

LifeCycle Methods: ejbFindByPrimaryKey The container-managed (CMP) version of BonusBean did not include an ejbFindByPrimaryKey implementation because in that case the container can locate database records by their primary keys; the primary key field is provided during deployment. In the bean-managed (BMP) version of BonusBean we must provide an implementation for this method and throw the SQLException. The CMP version throws RemoteException and FinderException only. If the find operation locates a record with the passed primary key, the primary key value is returned so the container can call the ejbLoad method to initialize BonusBean with the retrieved bonus and socsec data. One thing to notice about this class is that it returns a String value (primary key), while the corresponding declaration in the home interface deals with a Bonus class instance. The container uses the returned primary key to create the Bonus instance.

ejbFindByPrimaryKey: Code public String ejbFindByPrimaryKey(String primaryKey) throws RemoteException,FinderException, SQLException { System.out.println("Find by primary key"); try { //Establish database connection ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); //Use PreparedStatement to form SQL SELECT statement //to select from BONUS table ps = con.prepareStatement("SELECT socsec FROM BONUS WHERE socsec = ? "); ps.setString(1, primaryKey); //Use ResultSet to capture SELECT statement results ResultSet rs = ps.executeQuery(); //If ResultSet has a value, the find was successful, //and so initialize and return key if(rs.next()) { key = primaryKey; } else { System.out.println("Find Error"); } } catch (javax.naming.NamingException ex) { ex.printStackTrace(); } finally { ps.close(); con.close(); } //Return primary key return key; }

LifeCycle Methods: ejbLoad This method is called after a successful call to ejbFindByPrimaryKey to load the retrieved data and synchronize the bean data with the database data. public void ejbLoad() { System.out.println("Load method"); try { ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); ps = con.prepareStatement( "SELECT * FROM BONUS WHERE SOCSEC = ?"); ps.setString(1, this.socsec); ResultSet rs = ps.executeQuery(); //If ResultSet has a value, the find was successful if(rs.next()){ this.bonus = rs.getDouble(2); } else { System.out.println("Load Error"); } } catch (java.sql.SQLException ex) { ex.printStackTrace(); } catch (javax.naming.NamingException ex) { ex.printStackTrace(); } finally { try { ps.close(); con.close(); } catch (java.sql.SQLException ex) { ex.printStackTrace(); } }

LifeCycle Methods: ejbStore This method is called when a client sets or gets data in the bean to send the object data to the database and keep the bean data synchronized with the database data. public void ejbStore() { System.out.println("Store method"); try { DataSource ds = (DataSource)ic.lookup(dbName); con = ds.getConnection(); ps = con.prepareStatement("UPDATE BONUS SET BONUS = ? WHERE SOCSEC = ?"); ps.setDouble(1, bonus); ps.setString(2, socsec); int rowCount = ps.executeUpdate(); } catch (javax.naming.NamingException ex) { ex.printStackTrace(); } catch (java.sql.SQLException ex) { ex.printStackTrace(); } finally { try { ps.close(); con.close(); } catch (java.sql.SQLException ex) { ex.printStackTrace(); } }

LifeCycle Methods: ejbRemove This method is called when a client calls a remove method on the bean’s home interface. The JavaBean client in this example does not provide a remove method that a client can call to remove BonusBean from its container. Nevertheless, the implementation for an ejbRemove method is shown here. Upon a call by the container, ejbRemove gets the primary key (socsec) from the socsec instance variable, removes the bean from its container, and deletes the corresponding database row. public void ejbRemove() throws RemoteException { System.out.println("Remove method"); try { DataSource ds = (DataSource)ic.lookup(dbName); con = ds.getConnection(); ps = con.prepareStatement( "DELETE FROM BONUS WHERE SOCSEC = ?"); ps.setString(1, socsec); ps.executeUpdate(); } catch (java.sql.SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); try { ps.close(); con.close(); } catch (java.sql.SQLException ex) { ex.printStackTrace(); } }

LifeCycle Methods: ejbActivate When a bean has not been used in a long time, the container passivates it or moves it to temporary storage, where the container can readily reactivate the bean in the event a client calls one of the bean’s business methods. This method calls the getPrimaryKey method on the entity context so the primary key is available to clients querying the bean. When a query is made, the container uses the primary key to load the bean data. public void ejbActivate() { System.out.println("Activate method"); socsec = (String)context.getPrimaryKey(); }

LifeCycle Methods: ejbPassivate When a bean has not been used in a long time, the container passivates it or moves it to temporary storage where the container can readily reactivate the bean in the event a client calls one of the bean’s business methods. This method sets the primary key to null to free memory while the bean is in the passive state. public void ejbPassivate() { System.out.println("Passivate method"); socsec = null; }

LifeCycle Methods: setEntityContext & unsetEntityContext The former is called by the container to initialize the bean’s context instance variable. This is needed because the ejbActivate method calls the getPrimarykey method on the context instance variable to move a passive bean to its active state. The latter is called by the container to set the context instance variable to null after the ejbRemove method has been called to remove the entity bean from existence. Only entity beans have an unsetEntityContext method. public void setEntityContext(javax.ejb.EntityContext ctx){ System.out.println("setEntityContext method"); this.context = ctx; } public void unsetEntityContext(){ System.out.println("unsetEntityContext method"); ctx = null; }

Change the CalcBean and JBonusBean Code (I) Because BonusBean provides its own SQL code, the CalcBean.calcbonus method, which creates BonusBean instances, has to be changed to throw java.sql.SQLException. Here is one way to do make that change: public class CalcBean implements SessionBean { BonusHome homebonus; public Bonus calcBonus(int multiplier, double bonus, String socsec) throws RemoteException, SQLException, CreateException { Bonus theBonus = null; double calc = (multiplier*bonus); try { InitialContext ctx = new InitialContext(); Object objref = ctx.lookup("bonus"); homebonus=(BonusHome)PortableRemoteObject.narrow(objref, BonusHome.class); } catch (Exception NamingException) { NamingException.printStackTrace(); } //Store data in entity Bean theBonus=homebonus.create(calc, socsec); return theBonus; }

Change the CalcBean and JBonusBean Code (II) The JBonusBean class has to be changed to catch the SQLException thrown by CalcBean. DuplicateKeyExcpetion is a sublcass of CreateException, so it will be caught by the catch (javax.ejb.CreateException e) statement. public double getBonusAmt() { if(strMult != null){ Integer iMult = new Integer(strMult); int multiplier = iMult.intValue(); try { double bonus = ; theCalculation = homecalc.create(); Bonus theBonus = theCalculation.calcBonus(multiplier, bonus, socsec); Bonus record = theCalculation.getRecord(socsec); bonusAmt = record.getBonus(); socsec = record.getSocSec(); } catch (java.sql.SQLException e) { this.bonusAmt=0.0; this.socsec = "000"; this.message = e.getMessage(); } catch (javax.ejb.CreateException e) { } catch (java.rmi.RemoteException e) { } genXML(); return this.bonusAmt; } else { this.bonusAmt = 0; this.message = "None."; return this.bonusAmt; } }

Create the Database Table Because this example uses bean-managed persistence, you have to create by yourself the BONUS database table in the CloudscapeDB database. To make things easy, the database table is created with two scripts: createTable.sql and cloudTable.sh (Unix) or cloudTable.bat (Windows). For this example, the createTable.sql script goes in your ~/J2EE/Beans directory, and the cloudTable.sh (Unix) or cloudTable.bat (Windows/NT) script goes in your ~/J2EE directory.

createTable.sql drop table bonus; create table bonus (socsec varchar(9) constraint pk_bonus primary key, bonus decimal(10,2) ); exit;

cloudTable.bat rem cloudTable.bat rem Creates BONUS table in CloudscapeDB. rem rem Place this script in ~\J2EE rem To run: cd ~\J2EE\cloudTable.sh rem rem Change this next line to point to *your* rem j2sdkee1.2.1 installation rem set J2EE_HOME=\home\monicap\J2EE\j2sdkee1.2.1 rem rem Everything below goes on one line java -Dij.connection.CloudscapeDB= jdbc:rmi://localhost:1099/jdbc:cloudscape: CloudscapeDB\;create=true -Dcloudscape.system.home= %J2EE_HOME%\cloudscape -classpath %J2EE_HOME%lib\cloudscape\client.jar; %J2EE_HOME%lib\cloudscape\ tools.jar; %J2EE_HOME%lib\cloudscape\cloudscape.jar; %J2EE_HOME%lib\cloudscape\RmiJdbc.jar; %J2EE_HOME%lib\cloudscapeýicense.jar; %CLASSPATH% -ms16m -mx32m COM.cloudscape.tools.ij createTable.sql

Remove the JAR File You have to update the bean JAR file with the new entity bean code. If you have both beans in one JAR file, you have to delete the 2BeansJar and create a new one. The steps to adding CalcBean are the same as in Create JAR with Session Bean. The steps to adding BonusBean are slightly different. If you have the beans in separate JAR files, you have to delete the JAR file with BonusBean and create a new one.

Add BonusBean Entity Settings: Select Bean-managed persistence. The primary key class is java.lang.String. Note that the primary key has to be a class type. Primitive types are not valid for primary keys. Resource References: type jdbc/BonusDB in the proper column. Make sure Type is javax.sql.DataSource, and Authentication is Container. Transaction Management: Select Container-managed transactions (if it is not already selected). In the list below make create, findByPrimaryKey, getBonus and getSocSec required. Inspecting window: With 2BeansApp selected, click JNDI names. Assign calcs to CalcBean, bonus to BonusBean, and jdbc/Cloudscape to jdbc/BonusDB.