La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Disseny de la persistència

Presentaciones similares


Presentación del tema: "Disseny de la persistència"— Transcripción de la presentación:

1 Disseny de la persistència
Toni Navarrete Enginyeria del Software II – UPF 2002

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?

3 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.

4 Writing to an Object Stream. Example:
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();

5 Reading from an Object Stream. Example
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();

6 Serialization The serializable fields of a class can be defined two different ways. Default serializable fields of a class are defined to be the non-transient 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)}; }

7 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

8 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.

9 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.

10 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();

11 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");

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); Les columnes numerades des de 1 getFloat(“nom_camp”); o getFloat(1); getInt(“nom_camp”); o getInt(1); ...

13 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();

14 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(); }

15 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);

16 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()); }

17 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.

18 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

19 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

20 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

21 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

22 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.

23 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

24 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!! 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

25 A persistance service from a persistence framework: Ambysoft.com

26 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

27 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

28 No confondre EJB amb Java Bean.
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

29 Arquitectura d’un servidor web
Exemple: Apache web server

30 Arquitectura d’un motor de servlets (servlet engine)
Exemple: Tomcat

31 Arquitectura d’un servidor d’aplicacions
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

32 Tres tipus d’EJB Session EJBs Messaging 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

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

34 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

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)

36 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) }

37 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; }

38 Life-cycle of an entity bean

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(" "); 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); public ConverterBean() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}

40 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>

41 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>

42 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 container-managed i tenen relacions amb altres ejb, han de tenir interfaces locals i no remotes

43 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.

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.

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)

46 Deployment JAR (Java ARchives) WAR (Web 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

47 El deploytool del J2EE SDK

48 Ho utilitzem per nombrar
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

49 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)

50 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

51 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

52 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

53 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

54 JDO Keiron McCammon (Versant): Java Data Objects: the Future of Java Object Persistence

55 JDO JDOcentral.com: A comparion between Java Data Objects (JDO), Serialization and JDBC for Java Persistance

56 JDO Keiron McCammon (Versant): Java Data Objects: the Future of Java Object Persistence

57 JDO Libelis: Why JDO is a critical component of J2EE? White Paper

58 Adreces JDO http://www.jdocentral.com http://java.sun.com/products/jdo
(Canal sobre persistència de JavaWorld)


Descargar ppt "Disseny de la persistència"

Presentaciones similares


Anuncios Google