Enginyeria del software per web

Download Report

Transcript Enginyeria del software per web

Enginyeria del SW II: Disseny de la persistència
Disseny de la persistència
Toni Navarrete
Enginyeria del Software II – UPF 2002
Enginyeria del SW II: Disseny de la persistència
Pàgina 2
Continguts
• Objectiu: com fer per guardar les dades de forma
persistent, típicament a una BDR?
• Conversió de model de classes (model estàtic) a model
relacional
– supressió de l’herència (3 possiblitats)
– tractament de les relacions
• Gestió de la persistència (a les transparències)
– Serialization
– Amb un middleware: JDBC
• A la pròpia classe, o a una classe de connexió per a cada classe
de domini, o bé a una classe DBManager?
– Definint un framework propi (o gestor: llibre UOC)
• JSP and servlets
• Larman
• Exemples
– Utilitzant un framework comercial
– Utilitzant EJB, una plataforma més genèrica, estandaritzada
per Sun al J2EE
– Què és JDO?
Pàgina 3
Enginyeria del SW II: Disseny de la persistència
Serialization
• The key to storing and retrieving objects in a serialized
form is representing the state of objects sufficient to
reconstruct the object(s).
• Objects to be saved in the stream may support either
the Serializable or the Externalizable interface.
• For JavaTM objects, the serialized form must be able to
identify and verify the JavaTM class from which the
contents of the object were saved and to restore the
contents to a new instance.
– For serializable objects, the stream includes sufficient
information to restore the fields in the stream to a compatible
version of the class.
– For Externalizable objects, the class is solely responsible for
the external format of its contents.
Pàgina 4
Enginyeria del SW II: Disseny de la persistència
Serialization
• Writing to an Object Stream. Example:
// Serialize today's date to a file.
FileOutputStream f = new FileOutputStream("tmp");
ObjectOutput s = new ObjectOutputStream(f);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
Pàgina 5
Enginyeria del SW II: Disseny de la persistència
Serialization
• Reading from an Object Stream. Example
// Deserialize a string and date from a file.
FileInputStream in = new FileInputStream("tmp");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
Pàgina 6
Enginyeria del SW II: Disseny de la persistència
Serialization
• The serializable fields of a class can be defined two
different ways.
– Default serializable fields of a class are defined to be the nontransient and non-static fields.
• This default computation can be overridden by declaring a special
field in the Serializable class, serialPersistentFields.
• This field must be initialized with an array of ObjectStreamField
objects that list the names and types of the serializable fields.
– The modifiers for the field are required to be private, static, and
final.
– For example, the following declaration duplicates the default
behavior.
class List implements Serializable {
List next;
private static final ObjectStreamField[] serialPersistentFields
= {new ObjectStreamField("next", List.class)};
}
Pàgina 7
Enginyeria del SW II: Disseny de la persistència
JDO: problems (and adventages) of other
solutions
• Serialitzation
– Standard in every Java environment
– Easy to use
– Use Java classes as the data model
– Lacks features of a robust database
environment
– Lacks scalability required by most
applications
Pàgina 8
Enginyeria del SW II: Disseny de la persistència
JDBC
• The first thing you need to do is establish a connection
with the DBMS you want to use. This involves two
steps: (1) loading the driver and (2) making the
connection.
• Loading Drivers
• Loading the driver or drivers you want to use is very
simple and involves just one line of code. If, for
example, you want to use the JDBC-ODBC Bridge
driver, the following code will load it:
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Your
driver documentation will give you the class name to
use. For instance, if the class name is jdbc.DriverXYZ ,
you would load the driver with the following line of code:
• Class.forName("jdbc.DriverXYZ"); You do not need to
create an instance of a driver and register it with the
DriverManager because calling Class.forName will do
that for you automatically.
Pàgina 9
Enginyeria del SW II: Disseny de la persistència
JDBC
• Making the Connection
– The second step in establishing a connection is to
have the appropriate driver connect to the DBMS.
The following line of code illustrates the general
idea:
• Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
– Example:
• String url = "jdbc:odbc:Fred"; Connection con =
DriverManager.getConnection(url, "Fernanda", "J8");
– If you are using a JDBC driver developed by a third
party, the documentation will tell you what
subprotocol to use, that is, what to put after jdbc: in
the JDBC URL.
Pàgina 10
Enginyeria del SW II: Disseny de la persistència
JDBC
• A Statement object is what sends your SQL
statement to the DBMS. You simply create a
Statement object and then execute it, supplying
the appropriate execute method with the SQL
statement you want to send. For a SELECT
statement, the method to use is executeQuery .
For statements that create or modify tables, the
method to use is executeUpdate .
Statement object stmt;
Statement stmt = con.createStatement();
Pàgina 11
Enginyeria del SW II: Disseny de la persistència
JDBC
• JDBC returns results in a ResultSet
object, so we need to declare an
instance of the class ResultSet to hold
our results.
• The following code demonstrates
declaring the ResultSet object rs and
assigning the results of our earlier
query to it:
ResultSet rs = stmt.executeQuery("SELECT
COF_NAME, PRICE FROM COFFEES");
Enginyeria del SW II: Disseny de la persistència
Pàgina 12
String query = "SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
first()
next()
isFirst()
isLast()
getString(“nom_camp”); o getString(1);
de 1
getFloat(“nom_camp”); o getFloat(1);
getInt(“nom_camp”); o getInt(1);
...
Les columnes numerades des
Pàgina 13
Enginyeria del SW II: Disseny de la persistència
Prepared Statements
If you want to execute a Statement object many times, it will normally
reduce execution time to use a PreparedStatement object instead.
The main feature of a PreparedStatement object is that, unlike a
Statement object, it is given an SQL statement when it is created.
The advantage to this is that in most cases, this SQL statement will
be sent to the DBMS right away, where it will be compiled. As a
result, the PreparedStatement object contains not just an SQL
statement, but an SQL statement that has been precompiled. This
means that when the PreparedStatement is executed, the DBMS
can just run the PreparedStatement 's SQL statement without
having to compile it first.
Example:
PreparedStatement updateSales = con.prepareStatement("UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
Pàgina 14
Enginyeria del SW II: Disseny de la persistència
Prepared Statements (en un bucle)
PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast", "Espresso",
"Colombian_Decaf", "French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
}
Pàgina 15
Enginyeria del SW II: Disseny de la persistència
Transaccions (desactivar autocommit)
con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME
LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement(
"UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE
COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
Pàgina 16
Enginyeria del SW II: Disseny de la persistència
Transaccions (rollback)
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ");
System.err.println("rolled back");
con.rollback();
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
}
}
}
Pàgina 17
Enginyeria del SW II: Disseny de la persistència
Transaccions (tipus de nivells de aïllament)
Class Connection:
public void setTransactionIsolation(int level) throws SQLException
Attempts to change the transaction isolation level to the one given. The
constants defined in the interface Connection are the possible transaction
isolation levels.
Note: This method cannot be called while in the middle of a transaction.
static int
TRANSACTION_NONE
Indicates that transactions are not supported.
static int
TRANSACTION_READ_COMMITTED
Dirty reads are prevented; non-repeatable reads and phantom reads can
occur.
static int
TRANSACTION_READ_UNCOMMITTED
Dirty reads, non-repeatable reads and phantom reads can occur.
static int
TRANSACTION_REPEATABLE_READ
Dirty reads and non-repeatable reads are prevented; phantom reads can
occur.
static int
TRANSACTION_SERIALIZABLE
Dirty reads, non-repeatable reads and phantom reads are prevented.
Pàgina 18
Enginyeria del SW II: Disseny de la persistència
Novetat de JDBC 2: Scrollable ResultSets
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM
COFFEES");
The first argument is one of three constants added to the
ResultSet API to indicate the type of a ResultSet object:
TYPE_FORWARD_ONLY ,
TYPE_SCROLL_INSENSITIVE , and
TYPE_SCROLL_SENSITIVE .
The second argument is one of two ResultSet constants
for specifying whether a result set is read-only or
updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE .
Default: TYPE_FORWARD_ONLY and
CONCUR_READ_ONLY
Pàgina 19
Enginyeria del SW II: Disseny de la persistència
Novetat de JDBC 2: Scrollable ResultSets
Generally speaking, a result set that is
TYPE_SCROLL_INSENSITIVE does not reflect
changes made while it is still open and one that
is TYPE_SCROLL_SENSITIVE does
Example:
srs.absolute(4); // cursor is on the fourth row
srs.relative(-3); // cursor is on the first row
srs.relative(2); // cursor is on the third row
Four additional methods let you verify whether the
cursor is at a particular position. The position is
stated in their names: isFirst , isLast ,
isBeforeFirst , isAfterLast
Més mètodes per altes, baixes i modificacions
Pàgina 20
Enginyeria del SW II: Disseny de la persistència
JDBC: Connection pooling
• Una de les operacions més costoses és establir
la connexió amb la base de dades
• Utilització d’un pool de connexions
– Si quan s’ha de fer una connexió el pool està buit,
se’n crea una de nova
– Un cop que s’ha utilitzat una connexió no es
destrueix, queda al pool
– Veure codi al fitxer pool_simple.zip
– Problema: el pool creix sense límit
– Exercici: fer una millor implementació d’un pool
Pàgina 21
Enginyeria del SW II: Disseny de la persistència
Problems (and adventages) of JDBC
• Provides access to SQL
• Uses SQL’s relational data model
• Operations are expressed related to
tables, rows and columns
• Rarely portable across products (SQL not
really standardized)
• Does not support Java classes
• Procedural instead of object-oriented
• Processing data through SQL instead of
Java
Pàgina 22
Enginyeria del SW II: Disseny de la persistència
A persistance service from a persistence
framework
• A persistence framework (or persistence
layer) is a general-purpose, reusable, and
extendable set of types that provides
functionality to support persistance
objects.
• A persisstence service (or subsystem)
actually provides the service, and will be
created with a persistence framework
• A persistence service is ussally written to
work with RDBs, in which case is also
called an O-R mapping service.
Pàgina 23
Enginyeria del SW II: Disseny de la persistència
A persistance service from a persistence
framework
• Tipically, a persistence service must
translate objects into records (or some
other form of structred data such as XML)
and save them in a database, and
translate records into objects when
retrieving from a database
Pàgina 24
Enginyeria del SW II: Disseny de la persistència
A persistance service from a persistence
framework
• What is a framework?
– Simplifying: it is an extendable set of objects for related
functions. The quintessential example is a GUI framework,
such as Java’s AWT or Swing
– It offers a high degree of reuse
• Un exemple: Llibre LarmanApplying UML and Patterns,
2nd edition.
– Didàctic: Utilitza i comenta diversos patrons
– No es recomana desenvolupar-ne un!!
• http://www.ambysoft.com/persistenceLayer.pdf per
Scott W. Ambler
• Comercials:
– TOPLink, de webgain (VisualCafé entre d’altres), (abans de
TheObjectPeople) el més utilitzat
– Altres: CocoBase de Thought; Visual Business Sight
Framework (VBSF) de ObjectMatter
Enginyeria del SW II: Disseny de la persistència
Pàgina 25
A persistance service from a persistence
framework: Ambysoft.com
Pàgina 26
Enginyeria del SW II: Disseny de la persistència
Problems (and adventages)
• Propietary ORM (Object-Relational
Mapping)
– Significant risks in home-grown ORM
– Limitations of propietary ORM APIs. Adopting
a propietary API is risky
• Loss of encapsulation caused by the need to
define public getter and setter methods for each
persistence field
• Limited extensibility caused by the lack of support
for inheritance
• Lack of support for polimorphic references
• Overdependance on a single vendor
Pàgina 27
Enginyeria del SW II: Disseny de la persistència
EJB
• EJB=Enterprise Java Bean
• Escrit en Java, un EJB és un component de
servidor que encapsula lògica de negoci d’una
aplicació
• La lògica de negoci és el codi que satisfà els
propòsits d’una aplicació
– Per exemple, en una aplicació de gestió d’inventaris,
un ejb pot implementar la lògica de negoci en
mètodes anomenats controlarNivellInventari i
ferComandaProducte
– Un altre exemple: mantenir un “carretó de la
compra”
• Un EJB corre a un EJB-container, que és una
part d’un servidor d’aplicacions
Pàgina 28
Enginyeria del SW II: Disseny de la persistència
EJB versus Java Bean
• No confondre EJB amb Java Bean.
– Un EJB és un "deployable component". El
terme indica que existeix un ambient de
execució. Aquest ambien és el EJB-container
– Un Java Bean ha d’estar integrat amb altres
components per ser funcional
Enginyeria del SW II: Disseny de la persistència
Pàgina 29
Arquitectura d’un servidor web
• Exemple: Apache web server
Enginyeria del SW II: Disseny de la persistència
Pàgina 30
Arquitectura d’un motor de servlets (servlet
engine)
• Exemple: Tomcat
Pàgina 31
Arquitectura d’un servidor d’aplicacions
Enginyeria del SW II: Disseny de la persistència
• Exemples:
• J2ee server (només per desenvolupament)
• Tomcat (servlet engine) +Jboss (EJB-container)
• “Fully-J2EE-compliant”: WebLogic, Websphere,
Jrun, Oracle 9i Application Server, Sun ONE
Enginyeria del SW II: Disseny de la persistència
Pàgina 32
Tres tipus d’EJB
• Session EJBs
– Un Session EJB permet implementar una lògica
concreta, sol·lictiada per un client (que pot ser un
JSP/Servlet, un applet o altre EJB)
– N’hi ha que no guarden el seu estat (stateless
session ejb), per exemple, un ejb que implementa
una operació que no requereix guardar dades del
client, com una cerca, i n’hi ha que sí (statefull
session ejb), per exemple, un “carretó de la compra”
• Messaging EJBs
– Ofereixen funcionalitats de sistemes de missatgeria
asíncrona
– Poc emprats
Enginyeria del SW II: Disseny de la persistència
Pàgina 33
Tres tipus d’EJB
• Entity EJBs
– Un Entity ejb, al contrari que un session ejb, treballa
conjuntament amb un repositori persistent de dades
(típicament una BD)
– Així, un entity ejb pot llegir i escriure informació
externa al ejb-container (a una BD)
– Exemples: clients, comandes, productes...
– Típicament un entity ejb està mapejat amb una taula
d’una BDR, i cada instància del bean es
correspondrà amb una fila
– El ejb container dóna suport de pooling sense haver
de programar-ho
Pàgina 34
Enginyeria del SW II: Disseny de la persistència
Dos tipus de Entity EJB
• Bean Managed Persistence
– El propi EJB s’encarrega de definir la lògica per
accedir (manipular i consultar) a la BD. És a dir, s’ha
de programar manualment, típicament utilitzant
JDBC per sota
• Container Managed Persistence
– El propi ejb-container és qui s’encarrega de definir la
lògica per accedir a la BD
– Molt transparent!
• Aparentement, un “bean managed ejb” no té
massa sentit, però hi ha casos en què la lògica
d’accés és molt complexa i el ejb-container no
ho “sap” manegar
Enginyeria del SW II: Disseny de la persistència
Pàgina 35
Estructura d’un EJB
• Un EJB està format per una classe, dues
interfaces i un fitxer de “deployment”,
agrupats en un un fitxer jar
– Remote interface (Converter)
– Home interface (ConverterHome)
– El propi ejb (ConverterEJB o ConverterBean)
Pàgina 36
Enginyeria del SW II: Disseny de la persistència
Remote interface
• La interfície remota defineis els mètodes de
negoci que un client pot cridar. Els mètodes de
negoci s’implementarian a la classe del ejb
• Extèn EJBObject
• Un exemple (d’un session ejb):
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.math.*;
public interface Converter extends EJBObject {
public BigDecimal dollarToYen(BigDecimal dollars)
throws RemoteException;
public BigDecimal yenToEuro(BigDecimal yen)
throws RemoteException;
}
Pàgina 37
Enginyeria del SW II: Disseny de la persistència
Home interface
• La interfície home defineix els mètodes que
permeten a un client crear, trobar i eliminar un
ejb.
• Extèn EJBHome
• En l’exemple, conté només un mètode de
creació, que retorna un objecte que implementa
la interfície remota
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface ConverterHome extends EJBHome {
Converter create() throws RemoteException, CreateException;
}
Enginyeria del SW II: Disseny de la persistència
Pàgina 38
Life-cycle of an entity bean
Enginyeria del SW II: Disseny de la persistència
Pàgina 39
La
classe
ejb
• La classe ejb ha d’implementar els mètodes de negoci definits a la
interfície Remote i els mètodes relacionats amb el cicle de vida
(ejbCreate, ejbActivate...)
• Extèn SessionBean o EntityBean
• Exemple:
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.math.*;
public class ConverterBean implements SessionBean {
BigDecimal yenRate = new BigDecimal("121.6000");
BigDecimal euroRate = new BigDecimal("0.0077");
public BigDecimal dollarToYen(BigDecimal dollars) {
BigDecimal result = dollars.multiply(yenRate);
return result.setScale(2,BigDecimal.ROUND_UP);
}
public BigDecimal yenToEuro(BigDecimal yen) {
BigDecimal result = yen.multiply(euroRate);
return result.setScale(2,BigDecimal.ROUND_UP);
}
public ConverterBean() {}
public void ejbCreate() {}
Pàgina 40
Enginyeria del SW II: Disseny de la persistència
Codi del client index.jsp (1/2)
<%@ page import="Converter,ConverterHome,javax.ejb.*,
javax.naming.*, javax.rmi.PortableRemoteObject,
java.rmi.RemoteException" %>
<%!
private Converter converter = null;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
Object objRef = ic.lookup("
java:comp/env/ejb/TheConverter");
ConverterHome home =
(ConverterHome)PortableRemoteObject.narrow(
objRef, ConverterHome.class);
converter = home.create();
} catch (RemoteException ex) {
...
}
}
...
%>
<html>
<head>
<title>Converter</title>
</head>
Pàgina 41
Enginyeria del SW II: Disseny de la persistència
Codi del client index.jsp (2/2)
<body bgcolor="white">
<h1><center>Converter</center></h1>
<hr>
<p>Enter an amount to convert:</p>
<form method="get">
<input type="text" name="amount" size="25">
<br>
<p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
String amount = request.getParameter("amount");
if ( amount != null && amount.length() > 0 ) {
BigDecimal d = new BigDecimal (amount);
%>
<p><%= amount %> dollars are
<%= converter.dollarToYen(d) %> Yen.
<p><%= amount %> Yen are
<%= converter.yenToEuro(d) %> Euro.
<%
}
%>
</body>
</html>
Pàgina 42
Enginyeria del SW II: Disseny de la persistència
Interfícies locals i interfícies remotes
• El que hem vist és quan el client remot hi accedeix
• Una altra possibilitat és que hi accedeixin objectes
locals (de la mateixa JVM), s’utilitzen altres interfícies,
tot i que són equivalents:
– LocalHome (LocalConverterHome)
– Local Interface (LocalConverter)
• De nou, Local defineix els mètodes de negoci i
LocalHome els del cicle de vida i “finders”
• En cas de dubte: remot (es poden declarar les dues
però no és gens comú)
• Cas particular: els ejb d’entitat que són containermanaged i tenen relacions amb altres ejb, han de tenir
interfaces locals i no remotes
Pàgina 43
Enginyeria del SW II: Disseny de la persistència
Arquitectura de les EJB: Interfaces
• Well designed interfaces simplify the development and
maintenance of J2EE applications.
• Not only do clean interfaces shield the clients from any
complexities in the EJB tier, but they allow the beans to
change internally without affecting the clients.
• For example, even if you change your entity beans from
bean-managed to container-managed persistence, you
won't have to alter the client code.
• But if you were to change the method definitions in the
interfaces, then you might have to modify the client
code as well.
• Therefore, to isolate your clients from possible changes
in the beans, it is important that you design the
interfaces carefully.
Enginyeria del SW II: Disseny de la persistència
Pàgina 44
Remote vs local interfaces
• The decision on whether to allow local or remote access depends
on the following factors:
• Container-Managed Relationships
• If an entity bean is the target of a container-managed relationship, it must
use local access.
– Tight or Loose Coupling of Related Beans
• Tightly coupled beans depend on one another. For example, a completed
sales order must have one or more line items, which cannot exist without
the order to which they belong. The OrderEJB and LineItemEJB beans that
model this relationship are tightly coupled.
• Tightly coupled beans are good candidates for local access. Since they fit
together as a logical unit, they probably call each other often and would
benefit from the increased performance that is possible with local access.
– Type of Client
• If an enterprise bean is accessed by J2EE application clients, then it
should allow remote access. In a production environment, these clients
almost always run on different machines than the J2EE server.
• If an enterprise bean's clients are web components or other enterprise beans,
then the type of access depends on how you want to distribute your
components.
• Component Distribution
• J2EE applications are scalable because their server-side components can be
distributed across multiple machines. In a distributed application, for example,
the web components may run on a different server than the enterprise beans
they access. In this distributed scenario, the enterprise beans should allow
remote access.
Enginyeria del SW II: Disseny de la persistència
Pàgina 45
Exemples de EJB d’entitat
• Container-managed, sense relacions
(EJB, versió 1)
– Interface Product (remota)
– Interface ProductHome (home)
– Classe ProductEJB (classe ejb)
• Container-managed, sense relacions
(EJB, versió 2)
Pàgina 46
Deployment
Enginyeria del SW II: Disseny de la persistència
• JAR (Java ARchives)
– JAR ("Java Archives") és un format desenvolupat per Sun que
permet agrupar les classes Java per a la seva distribució.
S’utilitza sovint en qualsevol “ambient” de Java, ja que redueix
la càrrega d’administració degut a que només cal distribuïr un
únic fitxer. També comprimeix (redueix temps de baixada)
• WAR (Web ARchives)
– WARS o "Web Archive" és una especificació de Sun que
permet agrupar un conjunt de classes, servlets, JSPs,
documents HTML,... que formen una aplicación web en Java
– Permet interoperabilitat entre diferents Application servers
• EJB-JAR (EJB Java ARchives)
– Un EJB-JAR és la manera en què és distribuïts un ejb (amb les
seves interfaces)
• EAR (Enterprise ARchives)
– Un EAR simplement és un WAR i diversos EJB-JAR agrupats
– Es genera amb el deploytool del J2EE SDK
Enginyeria del SW II: Disseny de la persistència
Pàgina 47
El deploytool del J2EE SDK
Pàgina 48
Enginyeria del SW II: Disseny de la persistència
JNDI
• JNDI ("Java Naming Directory Interface")
és una especificació que permet localitzar
informació en diferents directoris
distribuïts
• Ho utilitzem per nombrar
– Connexions amb base de dades
– Altres ejb
– Ho podem configurar al deploytool
Pàgina 49
Enginyeria del SW II: Disseny de la persistència
JDO
• És una nova iniciativa de la comunitat per
crear un framework estandaritzat per a
persistència (de la mateixa que Swing ho
és per a interfície gràfica)
Pàgina 50
Enginyeria del SW II: Disseny de la persistència
JDO. Recordatori: problemes (i aventatges)
d’altres solucions
• Serialitzation
– Standard in every Java environment
– Easy to use
– Use Java classes as the data model
– Lacks features of a robust database
environment
– Lacks scalability required by most
applications
Pàgina 51
Enginyeria del SW II: Disseny de la persistència
JDO. Recordatori: problemes (i aventatges)
d’altres solucions
• JDBC
– Provides access to SQL
– Uses SQL’s relational data model
– Operations are expressed related to tables,
rows and columns
– Rarely portable across products (SQL not
really standardized)
– Does not support Java classes
– Procedural instead of object-oriented
– Processing data through SQL instead of
Java
Pàgina 52
Enginyeria del SW II: Disseny de la persistència
JDO. Recordatori: problemes (i aventatges)
d’altres solucions
• Propietary ORM (Object-Relational
Mapping)
– Significant risks in home-grown ORM
– Limitations of propietary ORM APIs. Adopting
a propietary API is risky
• Loss of encapsulation caused by the need to
define public getter and setter methods for each
persistence field
• Limited extensibility caused by the lack of support
for inheritance
• Lack of support for polimorphic references
• Overdependance on a single vendor
Pàgina 53
Enginyeria del SW II: Disseny de la persistència
JDO
• JDO: database facilities of JDBC and Java
integration of serialization
• JDO uses the Java object model
• Instances have unique identity (unique OID)
• It supports transactions
• Making instances is transparent
• Accessing and updating stored objects is
transparent
• Resumen: minimal intrusion and maximum
transparency
Pàgina 54
Enginyeria del SW II: Disseny de la persistència
JDO
Keiron McCammon (Versant): Java Data Objects: the Future of Java Object
Persistence
Pàgina 55
Enginyeria del SW II: Disseny de la persistència
JDO
JDOcentral.com: A comparion between Java Data Objects (JDO), Serialization and
JDBC for Java Persistance
Pàgina 56
Enginyeria del SW II: Disseny de la persistència
JDO
Keiron McCammon (Versant): Java Data Objects: the Future of Java Object
Persistence
Pàgina 57
Enginyeria del SW II: Disseny de la persistència
JDO
Libelis: Why JDO is a critical component of J2EE? White Paper
Pàgina 58
Enginyeria del SW II: Disseny de la persistència
Adreces JDO
• http://www.jdocentral.com
• http://java.sun.com/products/jdo
• http://www.javaworld.com/channel_conte
nt/jw-persistence-index.shtml
– (Canal sobre persistència de JavaWorld)