Nowbody calls me Ignacio. I’m plunchete, man!

SoC 2008 is on!!

Posted in Google Summer of Code by plunchete on February 25, 2008

With these words Leslie Hawthorn presented today the Google Summer of Code 2008. Google organized it three times before (2005, 2006, 2007). The Summer of Code program is an oportunity to contribute with one Open Source community, an portunity to earn some money coding and the oportunity to meet interesting people. Last year participated in the program 90 students from arround the world.

Personally, I took part in the program last year and was a great experience for me, this year I can’t participe becuase I finished my degree in november, next year I hope to be a mentor, this year I’m not feel ready for this yet. I will not take the new shirt :( !!! At least I have some friends who are going to apply this year.

If you want to participate in the Summer of Code program and have some doubts about the proposal, you can see my SoC proposal or if you want you can contact me via e-mail (plunchete _ gmail.com) or post a coment in this blog, I will be happy to help you.

If you are a 18 years or older student and you love coding you should apply!

My work in the Summer of Code

Posted in Google Summer of Code, OpenJPA by plunchete on September 11, 2007

Summer of Code finished at August 21th, but until yesterday my code didn’t part of the Apache OpenJPA project.

Since SoC finished I have refactored the tests classes, added new tests, added my Strategy in the MappingRepository and modified the DataCache, cache the streams is unadvisable, I have executed the tests in diferent databases and, for the moment, it runs in MySQL, SQL Server and Oracle. finally, after all those changes, my code was ready to check in.

Last several months were great, working in a OpenSource project, an important project, last several months I learned how OpenJPA works internally, and definetly I really enjoyed it!!.

When I started SoC my intention was continue contributing with the project that I have elected, and now after the SoC I’m sure that I’m going to continue contributing with the project.

Thanks Patrick for your work with me, and your help, you have been a fantastic mentor!! And, of course, thanks for your finally comment.

If someone wants to use this new feature, will need to download the latest SNAPSHOT and annotate the stream field (InputStream or Reader) like the example.

@Entity
public class Employee {
    ...
    @Persistent
    private InputStream photoStream;
...
}

And of course to use one the current databases supported.

Summer of Code has finished

Posted in Google Summer of Code, OpenSource by plunchete on August 27, 2007

Last days I couldn’t update the blog, I have been very busy, I have an exam on friday.

Last monday (21th) was the “pencils down” day in the SoC, mi work finished, I think that my work was good, but I have to wait until 31th to know the result. Next weekend I’m going to write a post about the project, the problems and other things.

I want thank to my mentor Patrick Linskey for his help with the project, his kindness and their lessons, thanks Patrick, you rocks! It’ve been a great summer :)

And finally thanks to The Apache Software Foundation for accept my proposal and to Google for the Summer of Code.

Thank you very much!

JPQL and how to delete objects in JPA

Posted in Google Summer of Code, Java, JPA, OpenJPA by plunchete on May 30, 2007

Continuing with the example Relations with JPA now I’ve written another example about querys and deleting objects.

JPA includes a mechanism to write querys called JPQL (Java Persistence Query Language) in this example we’re going to execute some querys and deleting some objects and their relations.

At the end of the last article we had this values in database:

[java] Organization: The Apache Software Foundation
[java] -Streaming LOB support (for OpenJPA) asigned to Ignacio Andreu
[java] -Maven Dependency Visualization asigned to Peter Kolbus
[java] Organization: Mono Project
[java] -Gendarme Tasks asigned to Néstor Salceda

And the next relations between entities:

  • A organization has many projects
  • Each projects is asigned to one organization
  • A project has one student
  • Each student is asigned to one project

Ok, if we remember the last example we used a Query to list all the organizations

Query q = em.createQuery("select o from Organization o");

This is a simple Query, now we’re going to write a Query with a WHERE clause.

JPQL provides us two methods for parameterized queries. First is positional parameter, using an integer prefixed by a question mark and second is named parameter, using an string prefixed by a colon. We can populate the Query calling the setParameter method.

If we are writing a Query with a positional parameter:

Query query = em.createQuery(select o from Organization o " 
                  + "where o.name like ?1);
query.setParameter(1, "The Apache Software Foundation");

And if we are writing a Query with a named parameter:

Query query = em.createQuery(select o from Organization o " 
                  + "where o.name like :name);
query.setParameter("name", "The Apache Software Foundation");

EntityManager povides other method to search an object by his primary key, the method find. In our class Organization the primary key is an int value, auto-increment. In out table the value of the Organization calls “The Apache Software Foundation” is 1. If whe want to load our object by the primary key:

Organization organization = em.find(Organization.class, 1);

Now we are going to delete our organization called “Mono Project” using JPQL. The process is the same that a select.

Query query = em.createQuery(delete from Organization o " 
                  + "where o.name like :name);
query.setParameter("name", "Mono Project");
int deleted = query.executeUpdate();

The Query provides methods to get the result like getResultList() when we want a List or getSingleResult() when we’re sure that we only have one match. Also The Query provides a method to set the maximun number of results setMaxResults(int number)

And now we going to list all the projects

Query q = em.createQuery("select p from Project p");
for (Project project : (List)q.getResultList()) {
	System.out.println("-"
                 + project.getOrganization().getName() 
                 + " - " + project.getName()
                 + " asigned to "
                 + project.getStudent().getName());
}

The output is

[java] -Streaming LOB support (for OpenJPA) asigned to Ignacio Andreu
[java] -Maven Dependency Visualization asigned to Peter Kolbus

Wow, all the projects asigned to “Mono Project” have been deleted too (and all the student asigned to this projects). If we remember we have these relations

@Entity
public class Organization {	

	...

	@OneToMany(cascade = CascadeType.ALL,
			mappedBy = "organization")
	@InverseLogical("organization")
	private ArrayList<Project> projects;

	...
@Entity
public class Project {	

	...

	@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	@JoinColumn(name="student_id")
	@InverseLogical("project")
	private Student student;

	...

It’s seems that our relations works :D

Another way is using the method remove of the EntityManager, but in this method we must indicate all the Object.

Query q = em.createQuery("select o from Organization o " 
		+ "where o.name like :name");
q.setParameter("name", "Mono Project");

// This is unsecure beacause name not is unique
// we can use the method setMaxResults(1)

Organization o = (Organization)q.getSingleResult();
em.remove(o);

The result is the same.

That is all, folks ;)

Relations with JPA

Posted in Google Summer of Code, Java, JPA, OpenJPA by plunchete on May 15, 2007

Continuing with the JPA Basic Example I’ve written another example with relations between Entities.

In the example we have three entities: Organization, Project, Student with this relations:

  • A organization has many projects
  • Each projects is asigned to one organization
  • A project has one student
  • Each student is asigned to one project

For this relations we need three anotations: @OneToOne, @OneToMany and @ManyToOne.

Now we are going to write our Organization entity:

@Entity
public class Organization {	

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "organization_id")
	private int idOrganization;

	@Basic
	@Column(nullable = false, length = 100)
	private String name;

	@OneToMany(cascade = CascadeType.ALL,
			mappedBy = "organization")
	@InverseLogical("organization")
	private ArrayList<Project> projects;

	public Organization(String name) {
		this.name = name;
	}
        // Getters and Setters
}

We used the anotation @OneToMany because we’re going to persist and Organization and we want to add projects to the organization and when we persist the organization the projects will be persist too.
The property cascade = CascadeType.ALL indicates that when we persist, remove, refresh or merge this entity all the entities held in this field would be persist, remove, delete or update. This property can have other values as:

  • CascadeType.PERSIST – When we persist and entity all the entities held in this field persist too. If you want to persist an entity and the fields dont use it fails.
  • CascadeType.REMOVE – When we delete an entity all the entities held in this field delete too.
  • CascadeType.REFRESH – When we refresh an entity all the entities held in this field refresh too.
  • CascadeType.MERGE – When we merde an entity all the entities held in this flied merged too

The following anotations are equivalent:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE,
             CascadeType.REFRESH, CascadeType.MERGE})
private ArrayList<Project> projects;

And

@OneToMany(cascade = CascadeType.ALL)
private ArrayList<Project> projects;

The propery mappedBy = “organization” indicates who’s the name of the organization entity in the project object.

The annotation @InverseLogical(“organization”) indicates that a field should be maintained bidirectionally. When we use this annotation OpenJPA managed the relation and updates the field oganization in the project entity.

Now we are going to write our Project entity:

@Entity
public class Project {	

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "project_id")
	private int idProject;

	@Basic
	@Column(nullable = false)
	private String name;

	@ManyToOne
	@JoinColumn(name="organization_id", nullable = false)
	private Organization organization;

	@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	@JoinColumn(name="student_id")
	@InverseLogical("project")
	private Student student;

	public Project(String name) {
		this.name = name;
	}
        // Getters and Setters
}

Now we use the annotation @ManyToOne to indicate the relation.
The annotation @JoinColumn(name=”organization_id”, nullable = false) indicates that the field can’t be null and the name on the table.
And finally we use the annotation @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) to manage our one-to-one relation between the project entity and the student.

Now we are going to write our Student entity:

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int studentId;

	@Basic
	@Column(nullable = false)
	private String name;

	@OneToOne
	@JoinColumn(name="project_id")
	private Project project;

	public Student(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
        // Getters and Setters
}

And our persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="1.0">
    <persistence-unit name="example" transaction-type="RESOURCE_LOCAL">
        <class>example.Organization</class>
		<class>example.Project</class>
		<class>example.Student</class>
        <properties>
            <property name="openjpa.jdbc.SynchronizeMappings"
                value="buildSchema"/>
            <property name="openjpa.ConnectionURL"
                value="jdbc:mysql://localhost/OpenJPARelations"/>
            <property name="openjpa.ConnectionDriverName"
                value="com.mysql.jdbc.Driver"/>
            <property name="openjpa.ConnectionUserName"
                value="user"/>
            <property name="openjpa.ConnectionPassword"
                value="password"/>
	    <property name="openjpa.InverseManager"
		value="true"/>
	    <property name="openjpa.Log"
		value="File=../RelationsExample.log,
                DefaultLevel=WARN,SQL=TRACE"/>
        </properties>
    </persistence-unit>
</persistence>

The property openjpa.InverseManager is necesary to manage inverse relations.
Finally the writer and the reader:

public void insertValues() {
	EntityManagerFactory factory = Persistence.
		createEntityManagerFactory("example", System.getProperties());

	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	Organization organization =
		new Organization(" The Apache Software Foundation");

	Project project =
		new Project("Streaming LOB support (for OpenJPA)");
	Student student = new Student("Ignacio Andreu");
	project.setStudent(student);
	organization.addProject(project);

	project = new Project("Maven Dependency Visualization");
	student = new Student("Peter Kolbus");
	project.setStudent(student);
	organization.addProject(project);

	em.persist(organization);

	organization = new Organization(" Mono Project");
	project = new Project("Gendarme Tasks");
	student = new Student("Néstor Salceda");
	project.setStudent(student);
	organization.addProject(project);

	em.persist(organization);

	em.getTransaction().commit();
	em.close();
	factory.close();
}

public void readValues() {
	EntityManagerFactory factory = Persistence.
	createEntityManagerFactory("example", System.getProperties());

	EntityManager em = factory.createEntityManager();

	Query q = em.createQuery("select o from Organization o");

	for (Organization organization : (List)q.getResultList()) {
		System.out.println("Organization: "
			+ organization.getName());
		if (organization.getProjects() != null &&
			organization.getProjects().size() > 0) {
			for (Project p : organization.getProjects()) {
				System.out.println("-"
					+ p.getName()
                                        + " asigned to "
					+ p.getStudent().getName());
			}
		} else {
			System.out.println("No proyects yet");
		}
	}
	em.close();
	factory.close();
}

The output is:

[java] Organization: The Apache Software Foundation
[java] -Streaming LOB support (for OpenJPA) asigned to Ignacio Andreu
[java] -Maven Dependency Visualization asigned to Peter Kolbus
[java] Organization: Mono Project
[java] -Gendarme Tasks asigned to Néstor Salceda

And this is all for the moment!

My Summer of Code proposal

Posted in Google Summer of Code by plunchete on April 17, 2007

Here is my entire proposal for the Summer of Code program, I hope that it helps to other students in the future.

-Project

OpenJPA is a 100% open-source implementation of the Java Persistence API (JPA), which is the persistence component for EJB in the Java EE 5 specification (part of JSR-220).

JPA combines the best ideas of other persintence technology, such as Hibernate, JDO and TopLink

The fields BLOB and CLOB of sql are translated for the Java programmer in the java.io.InputStream (for BLOBs) and java.io.Reader (for CLOBs) types, the objective of this project is to provide a serialization in database of these objects in a natural way.

-Deliverables

A code that das this functionality to the OpenJPA library in a transparent way for the user.

Battery of unity-test and functionality test of code in this Project with JUnit.

- Benefits for the Apache community:

Java Persistence API is one of the most important parts of the JEE specification, the project OpenJPA provides the community a free implementation of the persistant layer for EJB. The impementation of this new feature allows the user a m ore intuitive usage of the BLOBL and CLOB fields of SQL.

-Design / Approach:

Feature definition. Way of use: try to make it so it can be used in the most intuitive way

Binding definition among the java.io.InputStream and java.io.Reader objects for BLOB and CLOB respectively.

I believe that to provide the user of an abstraction of the database and execute the funtionality of this feature on several databases is something necesary, moreover something required.

- About me:

My name is Ignacio Andreu, I´m 22 years old from Zaragoza (Spain) and I´m finishing my studies of Computer Engineering.

One year ago I worked as Java Developer in “cierzo development” ( http://www.cierzo-development.com/ ) for 3 monts. I developed an aplication for web positioning, using open-source tools like heritrix as crawler and SQL Server as data base.

Actualy I’m working as J2EE developer in Tool Banking Solutions while finishing my university studies ( http://www.tb-solutions.com/ ) making a web aplication for the Comunity of Madrid, the application is a pay plataform to pay taxes. This aplication uses electronic certificates and criptography.

I was co-founder of the Java User Group of my university and I have given courses, as teacher, in my university about J2EE.

Knowledge in Java platform: J2ME, J2SE, JSE, J2EE, Servlets, JSP’s, Struts, JDBC, Hibernate, Swing, MIDP 1.0 y 2.0, Threads, Java2d, Java3d, Reflection, Collections.

Regarding academical achievements I got graduated with honors in the subject “Practicas de Programación”, the aplication I made consisted of a framework for the creation of interfaces for Swing user using XML files.

I deeply relieve that taking part in the Google Summer of Code is a fantastic oportunity for a student to get envolved in a project of free software surrounded by professionals. I can´t wait to get started!

Follow

Get every new post delivered to your Inbox.