Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Java / Java SE
Article

Persist in DataBase with AspectJ (AOP)

Rate me:
Please Sign up or sign in to vote.
2.75/5 (4 votes)
6 Sep 20046 min read 42.5K   583   13   5
One of the multiple forms to give persistence in data base to an object of a class with oriented programming to aspects (AOP) in AspectJ

Persist in Database with AspectJ (AOP)


Sumary:
One of the multiple forms to give persistence in data base to an object of a class.

Author:
Mariano Lorente
Programemos en AspectJ

Fecha:
30 de Agosto 2004

Level:
Middle

Enviromment:
Eclipse, Java, AspectJ, JDBC, Aspect Object Programming (AOP)





Indice:
Introduction
Aspect abstract
Aspect clase Cliente
Test
Conclusion


Introduction

The power to in a while provide dice to an object of a class persistence, can make see the capacity us that has the Aspects. Since we can give this behavior to the objects of a class, that does not have it, if to have to change its codification.

There will be people who will understand that the persistence is not an aspect of a class, since a part inherent of the class at issue can be considered and therefore it is not possible to be understood like an aspect, mainly when speech of business objects. But the certain thing is that when we spoke of ' objects of negotiated we say this same one and not ' objects of businesses persistentes'. As it is understood a business object contains the logic of the business of supports this class. Another aspect is as this information in a data base keeps to make it persistent.

Let us consider another situciación, we suppose that we have developed several systems of persistence, one that stores the data in XML, another one in flat text files, another one in data base.

Now we put the following example of migration.

In a while dice we have developed an application in which we have a class of Configuration that stores the data of configuration of the application, due to the initial use of this application we have considered which we are going to keep these data from configuration in a file XML, but with time this application has grown and now it is that the configuration data we needed them to have a network since is necessary that they share all the corporative applications in installed her, for it we have chosen to keep the data in data base since all the equipment will be able to have access to the data base. If the class were programmed with aspects Configuration it would not undergo any change since the only thing that we would change would be the aspect to apply to this class.

Next we are going to see the way that has been followed to give persistence to the objects of a class.



Aspect abstract

In the first place first that has been developed it has been an abstract aspect called Persistence that goes has to allow to extend it with other aspects. This abstract aspect contains all the points of abstract cuts that define the behavior of the aspect in a while given.

The declaration of the points of abstract cuts is due to sobrewrite in the aspect that extends the abstract aspect, capturing the execution of the tie points that wish for the execution of the point of wished cut.

This abstract aspect as well extends the CapaDatos class that contains all the functionality to give persistence to an object.

When extending the CapaDatos class we accede to the functionality of this class from the aspect, just as if one had declared all its functions within the own aspect.


Figura 1. Persistencia.aj

package persistencia_Aspect;

import java.sql.*;
/**
 * @author mlorente@programemos.com
 */
abstract aspect Persistencia extends CapaDatos {
    
  declare parents : FormularioCliente implements ObjetosRelacion;
        
  Persistencia() {
    super();
    System.out.println("constructor Persistencia");
  }
    
  abstract pointcut quieroLeer();
  abstract pointcut quieroGrabar();
  abstract pointcut quieroBorrar();
    
  after() : quieroLeer() {
    leer();
  }
    
  before() : quieroGrabar() {
    grabar();
  }
    
  before() : quieroBorrar() {
    borrar();
  }
    
  public void FormularioCliente.addObjetoRelacion(Object obj) {
    addObjeto((Cliente)obj);
  }
}

The firts we can see is the following code:

declare parents : FormularioCliente implements ObjetosRelacion.

Here this indicating itself to him that the FormularioCliente class (In one more a developed implementation a form would be a class representing bases) goes has to implement the ObjetosRelacion interface.

At the end of the declaration of the aspect the following code can be seen:
public void FormularioCliente.addObjetoRelacion(Object obj) {
    addObjeto((Cliente)obj);
}

Where the method has been implemented that contains the ObjetosRelacion interface.
Not being the intention of this article treating the relations between objects, a basic implementation and of the relations between objects has been made minimum.

Will be an aspect the relations of objects?

Next we are going to see the most important part of the declaration of the aspect.

abstract pointcut quieroLeer();
abstract pointcut quieroGrabar();
abstract pointcut quieroBorrar();

after() : quieroLeer() {
  leer();
}

before() : quieroGrabar() {
  grabar();
}

before() : quieroBorrar() {
  borrar();
}

Three points of abstract cuts are declared, that will be due to sobrewrite in the aspects that the present one extends.
As we can see this does not prevent that they are possible already to be declared advice for these points of cut. Within these advice is called to the methods contained within the CapaDatos class since we have extended to him and for that reason we can make use of them.



Aspect Cliente

One of the idea at the time of carrying out this small project, has been to have to write the smaller code possible to give persistence to the objects of a certain class. And a code similar to the PersistenciaCliente aspect will be the one that we will have to write to give persistence to the objects that we wish.

Figura 2.  PersistenciaCliente.aj

package persistencia_Aspect;

import java.sql.*;
/**
 * @author mlorente@programemos.com
 */
aspect PersistenciaCliente extends Persistencia {

  PersistenciaCliente() {
    System.out.println("constructor PersistenciaCliente");
  }
    
  pointcut quieroLeer() : execution(* *.leer_click());
  pointcut quieroGrabar() : execution(* *.grabar_click());
  pointcut quieroBorrar() : execution(* *.borrar_click());

  public String[] clave() {
    String[] a = new String[] {"IdCliente={$getId}"};
    return a;
  }
    
  public String sqlIdentityField() {
    return "{$setId}";
  }
    
  public String sqlSelect() {
    return "SELECT IdCliente{$setId}, Nombre{$setNombre}, Email{$setEmail} FROM Cliente";
  }
  
  public String sqlUpdate() {
    return "UPDATE Cliente SET Nombre='{$getNombre}', Email='{$getEmail}'";
  }
    
  public String sqlInsert() {
    return "INSERT INTO Cliente(Nombre, Email) VALUES('{$getNombre}', '{$getEmail}')";
  }
    
  public String sqlDelete() {
    return "DELETE FROM Cliente";
  }
}

Once sight all the code that composes the PersistenciaCliente aspect we are going to enter to develop the detail of the same one.

In the following code:

pointcut quieroLeer() : execution(* *.leer_click());
pointcut quieroGrabar() : execution(* *.grabar_click());
pointcut quieroBorrar() : execution(* *.borrar_click());

we can suspect that it is the code that on writes the points of abstract cuts defined in the aspect Persistence. And we suspected well because he is that what does. As it indicates the first point of cut we want that the cut point is executed when the execution of the method is captured leer_click.

As we can appreciate has not declared no advice with which the code of the advices of the abstract aspect will be executed Persistence.

The rest of methods is not more than on writing of methods of the CapaDatos class since the abstract aspect Persistence extends this class and the PersistenciaCliente aspect extends the aspect Persistence.

Note: the words that accompany sentence SQL and key it is not more than a form to indicate in that functions we want to establish the values or of which functions we want to recover the values. Thus we are parseando the values of the fields of the layer from data to the fields of the business object.

Let us take as example the following sentence:
SELECT IdCliente{$setId}, Nombre{$setNombre}, Email{$setEmail} FROM Cliente

In previous sentence SQL it is being indicated to him that it recovers of the data base the IdCliente, Name and email of the table Client. Evidently this is not code SQL but it goes has to serve us to parse between the data of the database and the functions of the business object Client. Thus we will establish or recover the values of the methods of the business object.



Test

Finally single it is to see the class that goes has to allow to us to make the opportune tests. It is necessary to mention the following code formulario.addObjetoRelacion(cliente) since object relates them to the FormularioCliente class. Account is necessary to occur that the FormularioCliente class does not contain the method at issue and that this provides through the abstract aspect Persistence to him.

package persistencia_Aspect;
/**
 * @author mlorente@programemos.com
 */
import java.lang.reflect.*;
public class Test {
  public static void main(String[] args) {
    FormularioCliente formulario=new FormularioCliente();
        
    Cliente cliente=new Cliente();
    cliente.setId(1);
    Cliente cliente2=new Cliente();
    cliente2.setId(2);
        
    formulario.addObjetoRelacion(cliente);
    formulario.addObjetoRelacion(cliente2);
    formulario.leer_click();

        
    System.out.println("nombre del 1: " + cliente.getNombre() + 
      " ruta: " + cliente.getEmail());
    System.out.println("nombre del 2: " + cliente2.getNombre() + 
      " ruta: " + cliente2.getEmail());
    
    cliente.setNombre("nombre del 1 cambiado");    
    formulario.grabar_click();    


    cliente2.setNombre("nombre del 2 cambiado");
    Cliente cliente3=new Cliente();
    cliente3.setNombre("nuevo");
    cliente3.setEmail("Nueva");
        
    formulario.addObjetoRelacion(cliente3);
    formulario.borrar_click();
  }
}


Conclusion

Evidently this is not the definitive solution to give persistence to an object of a class, but it approaches us one of the multiple forms to do it.

Maybe you throw in lack the code of the CapaDatos class, but it is provided in zip of the example, as well as the one of other classes or interfaces nonmentioned.



Programemos en AspectJ


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Spain Spain
Mariano Lorente is programmer analyst in a technological company of Zaragoza (Spain), in addition to webmaster of www.programemos.com Web dedicated to the oriented programming aspects (AOP) with AspectJ and articles of programming.

In its worked race to in systems like AS/400, CICS and lately in Windows, languages like COBOL/400, RPG, COBOL/CICS, Visual Basic, C#, Asp, Asp.Net, XML, Xslt, SQL Server, Oracle, etc…

MCP - Designing and Implementing Desktop Applications with Microsoft Visual Basic 6.0

MCP - Designing and Implementing Distributed Applications with Visual Microsoft Basic 6.0

Comments and Discussions

 
Generalsee Java Persistence Aspect Pin
Anonymous9-Nov-04 5:41
Anonymous9-Nov-04 5:41 
GeneralLooks interisting ... lost me on the first two sentences Pin
coozer15-Sep-04 14:54
coozer15-Sep-04 14:54 
GeneralSeems to be interesting - but why Spanish Pin
Hans J. Schroeder10-Sep-04 22:02
Hans J. Schroeder10-Sep-04 22:02 
GeneralRe: Seems to be interesting - but why Spanish Pin
mlorente13-Sep-04 11:28
mlorente13-Sep-04 11:28 
GeneralRe: Seems to be interesting - but why Spanish Pin
박기복19-Sep-04 3:34
박기복19-Sep-04 3:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.