[ENGLISH VERSION] Spring Roo basic example with PostgreSQL

 
Vamos a hacer unas pruebas iniciales con Spring Roo Project para ver si lo incluimos en los entornos de desarrollo del proyecto Learning Project. Para hacer un desarrollo lo más rápido posible y hacer una evaluación vamos a utilizar una única tabla de las que se recogen en el proyecto aquí tienes toda la información.

Spring Roo

A next-generation rapid application development tool for Java developers. With Roo you can easily build full Java applications in minutes.Spring Roo

En definitiva vamos a ver que aplicación CRUD podemos generar con Spring Roo para la base de datos customerdbroo donde vamos a crear la tabla cb_language con la siguiente estructura en base de datos:

Esquema de la tabla cb_language

Esquema de la tabla cb_language

cb_language

Tabla con los idiomas registrados en la aplicación, se podrá relacionar con múltiples tablas.

En este tutorial aprenderemos a hacer una aplicación Web desde cero usando Spring Roo con PostgreSQL, lo que haremos:

Características Spring Roo

Spring Roo se presenta como una herramienta ligera para hacer más rápido la consecución de resultado instantáneos, veremos si estos se adecuan a nuestras necesidades básicas, el código generado es Java por lo que entendemos que podremos personalizar todo el código generado. o comprobaremos.
Spring Roo se pretende diferenciar de otras herramientas por:

  • Resultados rápidos
  • 100% desarrollado en Java
  • Fácil de usar
  • Rápido y sencillo de borrar
  • Totalmente libre
  • Comunidad activa
  • Integración tecnológica
  • Extensión mediante Roo add-ons
  • Arquitectura con certificación Spring

Preparación del entorno

Para estas pruebas vamos a trabajar con el entorno proporcionado por Spring Tool Suite (STS), aquí puedes descargar la versión que necesites para tu sistema operativo, Spring Tool Suite (STS) proporciona soporte para Spring Roo 2.0.0 está disponible a partir de STS 3.7.0, en el enlace de la descarga encontrarás toda la información.

Ahora vamos a incluir Roo en nuestro STS IDE:

  • Abre tu IDE STS
  • Abre el cuadro de mandos (dashboard) de STS
  • Haz clic en el tab Extensions y busca Spring Roo
  • Instala Spring IDE – Roo Extension.
  • Reinicia STS

Configurando Spring Roo 2.0.0 en tu STS:

  • Selecciona en el menú Window y abre «Preferences > Spring > Roo Support»
  • En «Roo Support» pulsamos el botón «Add» para la nueva instalación.
  • En «Roo Configure Roo Installation» pulsa el botón «Browse», entonces selecciona el directorio en el que tienes descomprimido Spring Roo 2.0.0
  • Confirma la instalación
  • Ahora Roo está instalado en tu STS

Con esto ya dejamos nuestro IDE configurado para utilizar Spring Roo.

Ahora solo falta que instalemos PostgreSQL en nuestro equipo si no lo tenemos ya instalado, en la publicación Tutorial Postgresql (1): Preparando el entorno tienes toda la información y los enlaces necesarios para la descarga y configuración básica.
 

Creación del proyecto y configuración

Con el IDE STS ya preparado para Spring Roo, vamos a crear el proyecto, para ello nos dirigimos al panel de control (dashboard) donde encontraremos una opción: Spring Roo Project que nos permite generar un proyecto Spring Roo como puedes ver en la imagen:

Spring Roo Project Creación del proyecto

Spring Roo Project Creación del proyecto

Ahora en la pantalla de creación de nuevo rellenamos la información que se nos pide como se muestra en la imagen y le damos a siguiente (next):

Spring Roo Project Creación del nuevo proyecto

Spring Roo Project Creación del nuevo proyecto

Una vez hecha la selección nos aparecerá el siguiente mensaje en pantalla: «Please click ‘Finish’ to create the new project using Roo», y solo nos quedará pulsar el botón de FINISH. Ahora ya tenemos nuestro proyecto creado y la consola para Spring Roo que utilizaremos para ir creando la unidad de persistencia, la tabla, y la generación MVC del proyecto web, a continuación vamos a explicar su uso utilizándola, en la imagen puedes ver el proyecto y la consola que utilizaremos.

Vamos a realizar nuestra configuración con PostgreSQL para la base de datos que vamos a crear y que llamaremos customerdbroo.

jpa setup --provider HIBERNATE --database POSTGRES --databaseName customerdbroo

Al ejecutar esto en la consola Roo nos muestra las acciones realizadas, recuerda refrescar el proyecto para recargar los nuevos ficheros creados:

Spring Roo Project - Roo configuración de la base de datos

Spring Roo Project – Roo configuración de la base de datos

Como puedes ver en la imagen se han creado los ficheros de configuración de la aplicación, la persistencia y el que vamos a tocar ahora database.properties donde completamos el usuario y contraseña de acceso a la base de datos, así quedará finalmente:

#Updated at Wed Nov 04 23:04:43 CET 2015
#Wed Nov 04 23:04:43 CET 2015
database.driverClassName=org.postgresql.Driver
database.url=jdbc\:postgresql\://localhost\:5432/customerdbroo
database.username=xulescode
database.password=xulescode

 
Te recomiendo que explores los ficheros creados para familiarizarte con el entorno, aunque de momento el único fichero que tenemos que tocar es el que hemos configurado.
 

Creación de la entidad para cb_language

Ahora ya podemos crear nuestros objetos del dominio y los campos con los definiremos nuestra clase para cb_language. Ahora usaremos el comando entity jpa para crear nuestra entidad, este comando tiene una serie de atributos de los cuales vamos a utilizar

  • class que nos sirve para especificar con que dominio estamos, y que después, cuando creemos otras tablas, o posteriormente, queramos añadir nuevos campos nos permitirá especificar que entidad estamos modificando.
  • testAutomatically atributo que crea los test de integración para un objeto de dominio

Una vez aclarado esto vamos a crear la entidad CbLanguage ejecutando en la consola Roo:

entity jpa --class ~.domain.CbLanguage --testAutomatically

 
Acuérdate de refrescar el proyecto para ver las acciones realizadas, estas se indican en la consola como sigue:

roo> entity jpa --class ~.domain.CbLanguage --testAutomatically
Created SRC_MAIN_JAVA/org/xulescode/mode/domain
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage.java
Created SRC_TEST_JAVA/org/xulescode/mode/domain
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand.java
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest.java
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Configurable.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_Entity.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_ActiveRecord.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_ToString.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_DataOnDemand.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest_Roo_IntegrationTest.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest_Roo_Configurable.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_Configurable.aj

 
Ahora vamos a añadir los campos, el primero que vamos a añadir es idlanguage que según la estructura definida inicialmente para la tabla debería ser la clave primaria, en esta primera aproximación a Spring Roo no he encontrado la forma de indicar que quiero que esta sea la clave primaria y con este nombre, al final veremos porque sucede esto y cual es la clave primaria que nos genera Spring Roo automáticamente. Para añadir un nuevo campo la estructura es sencilla usamos el comando field seguido del tipo de dato y ahora podemos usar algunos atributos, en este enlace tienes más atributos disponibles, los que utilizamos aquí son los siguientes:

  • –fieldName idlanguage indicamos el nombre del campo
  • –notNull indicamos que el campo no puede ser NULL.
  • –sizeMax 6 indicamos el tamaño máximo, también podemos indicar el mínimo con sizeMin
  • –class ~.domain.CbLanguage como ya expliqué antes nos sirve para indicar con que dominio estamos trabajando, ahora realmente no nos haría falta porque ya estamos trabajando dentro del dominio CbLanguage

Con lo que la creación de nuestro primer campo quedaría así:

field string --fieldName idlanguage --notNull --sizeMax 6 --class ~.domain.CbLanguage

 
Este es el resultado que se muestra en nuestra consola para nuestro primer campo, lo indico simplemente para que te fijes que ahora en la consola estamos trabajando con el dominio CbLanguage (~.domain.CbLanguage roo>):

~.domain.CbLanguage roo> field string --fieldName idlanguage --notNull --sizeMax 6 --class ~.domain.CbLanguage
Updated SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage.java
Updated SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_DataOnDemand.aj
Updated SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_ActiveRecord.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_JavaBean.aj

 
Añadimos el resto de campos sin profundizar de momento mucho más:

field string --fieldName namelanguage --notNull --sizeMax 60 --unique 
field string --fieldName isactive --notNull --sizeMax 1 --value "N"
field string --fieldName languageiso --sizeMax 2 
field string --fieldName countrycode --sizeMax 2 
field string --fieldName isbaselanguage --notNull --sizeMax 1  --value "N"

 
Esta es el resultado de los campos que hemos creado en CbLanguage:

package org.xulescode.mode.domain;
import org.springframework.roo.addon.javabean.annotations.RooJavaBean;
import org.springframework.roo.addon.javabean.annotations.RooToString;
import org.springframework.roo.addon.jpa.annotations.activerecord.RooJpaActiveRecord;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.persistence.Column;
import org.springframework.beans.factory.annotation.Value;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class CbLanguage {

    /**
     */
    @NotNull
    @Size(max = 6)
    private String idlanguage;

    /**
     */
    @NotNull
    @Column(unique = true)
    @Size(max = 60)
    private String namelanguage;

    /**
     */
    @NotNull
    @Value("N")
    @Size(max = 1)
    private String isactive;

    /**
     */
    @Size(max = 2)
    private String languageiso;

    /**
     */
    @Size(max = 2)
    private String countrycode;

    /**
     */
    @NotNull
    @Value("N")
    @Size(max = 1)
    private String isbaselanguage;
}

 
Ahora ejecutamos los test que hemos creado automáticamente con el comando para maven perform tests, como se explica con más detalle en el apartado de la documentación de referencia. Utilizando nuestro STS vamos a Run As > Maven test
Podemos personalizar nuestro código Java, si quieres ver algo más aquí tienes un ejemplo: Edit, modify and customize the Roo-generated code, en esta publicación no entraremos en este apartado.

 

Resolviendo dependencias

Una vez finalizado esto, y por lo menos en mi caso, se observa en el proyecto la indicación de que tenemos errores en nuestro fichero pom.xml, aquí fue donde perdí más tiempo en el tutorial, hasta que me dí cuenta que había problemas de configuración en las definiciones utilizadas en el proyecto, estás son las correcciones que yo he hecho para que todo funcione correctamente:

		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
		<repository>
			<id>org.springframework.maven.release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://repo.springsource.org/libs-release-local</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>

 

Creación y configuración del MVC para la web

Siguiendo la referencia del proyecto de ejemplo de la documentación de Spring Roo, a continuación, generamos la aplicación Web con la que gestionaremos los idiomas de la clase CbLanguage, así que para ello vamos a ejecutar los comandos web mvc. En primer lugar usaremos web mvc setup para configurar todos los controladores de la aplicación seguido a continuación del comando web mvc all:

~.domain.CbLanguage roo> web mvc setup
~.domain.CbLanguage roo> web mvc all --package ~.web

 
Una vez finalizado ya tenemos lista nuestra aplicación para funcionar.
 

Despliegue del proyecto y pruebas

Antes de ejecutar nuestro proyecto situándonos sobre el fichero pom.xml ejecutamos Run As >Maven install, una vez hecho esto debemos compilar nuestro proyecto, por eso, situándonos desde el mismo sitio ejecutamos ahora Run As >Maven build, y nos aparecerá un menú, tal que así:

Spring Roo Project Roo Maven package

Spring Roo Project Roo Maven package

Estamos utilizando M2Eclipse que nos proporciona una integración para Apache Maven dentro del IDE, como ves en la foto aparecen varias opciones, en tu caso, aparecerá una sin ninguna definición, y esto es porque aún no has definido ninguna meta (Goal), selecciona uno y donde pone Goals introduce package, que es el comando para compilar nuestro proyecto.
 
Hecho esto ya estamos listos para ejecutar nuestro proyecto, sitúate encima de él y selecciona la opción Run As > Run on Server, este es el resultado:

Spring Roo Project Roo Web

Spring Roo Project Roo Web

Creación de un nuevo idioma:

Spring Roo Project Roo Web Crear elemento

Spring Roo Project Roo Web Crear elemento

Listado de los idiomas creados para nuestra entidad CbLanguage, donde tenemos las opción de edición, ver y borrado, completando así nuestra aplicación CRUD.

Spring Roo Project Roo Web Listado de los elementos

Spring Roo Project Roo Web Listado de los elementos

Como puedes ver la aplicación está funcionando y lista, con la configuración que tenemos cada vez que ejecutemos el proyecto se creará de nuevo la base de datos, si no queremos esto simplemente editamos nuestro fichero persistence.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>
            <!-- Uncomment the following two properties for JBoss only -->
            <!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
            <!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
        </properties>
    </persistence-unit>
</persistence>

 
Aquí, modificamos la propiedad hibernate.hbm2ddl.auto, y la cambiamos de create a update, así, ya no borraremos los datos cada vez que ejecutemos el proyecto.

Finalizado el tutorial estas son mis conclusiones

  • Spring Roo es una herramienta potente para generar una aplicación rápidamente tal y como se promete.
  • No me gusta de Spring Roo la limitación a la hora de generar código por la consola Roo, como por ejemplo, definir tu propia clave primaria, entiendo que si se puede hacer, pero a posteriori, modificando el código Java, quiero explorar más sobre esto, pero es la parte que menos me gusta.
    • Corrijo mi precipitada conclusión para señalar como me indican en un comentario que si podemos identificar nuestra propia clave primaria, y de manera muy fácil, añadimos los siguientes parámetros –identifierField idLanguage –identifierType java.lang.String, y ya se genera, la clave primaria.
    • field string --fieldName idlanguage --notNull --sizeMax 6 --identifierField idLanguage --identifierType java.lang.String --class ~.domain.CbLanguage
      
    • Lo que sigue sin convencerme del todo es la generación en la consola Roo de las entidades, esto es un apreciación personal ya que su funcionalidad hay está, me llama o me gusta más la opción de ingeniería inversa, que probaré sin lugar a dudas.
  • La generación inicial de la estructura web es rápida y sencilla.
  • No me gustan las escasas posibilidades que se introducen en la generación con web mvc
    • También corrijo está conclusión por que no expresa exactamente lo que yo quería, vengo de probar Openxava, donde las cosas se hacen de otra forma, y me gusto más (de momento) su planteamiento. Para valorar en su justa medida a Spring Roo necesito hacer más pruebas, y ver como más detalle los add-ons que aporta y que si me parencen muy interesante.
    • Lo que te genera el Scaffold en una versión sencilla de lo mínimo necesario para la gestión de la entidad que has generado. Esto, por supuesto, es modificable y ampliable como tu creas necesario en tu proyecto. Además Spring Roo ofrece la posibilidad de automatizar operaciones generando complementos (add-on) que puedes instalar de forma fácil y sencilla gracias a los nuevos cambios introducidos en la versión 2.0 para su gestión y instalación como add-on suite aporte por Jose Manuel Vivó Arnal
  • Las ventajas que tiene Spring Roo es toda la integración con Spring con lo que fácilmente vamos a poder usar Spring Security, por ejemplo, ejecutando por consola: security setup.

Conclusión

Finalizando, me gusta la integración con Spring y sus herramientas, pero no me convence ni la creación de tablas, ni la generación del esqueleto de la web, ya que creo que debería aportar más opciones, esta es una conclusión inicial ya que la inclusión de Add-ons y la ingeniería inversa podrían cambiar totalmente mi apreciación inicial.Xules

 
Me queda pendiente probar algo más prometedor en relación con la base de datos, y es que hay una opción para hacer ingeniería inversa de nuestra base de datos ya creada, y esta opción si funciona bien si podría cubrir mis expectativas creadas, ya que inicialmente me quedo un poco decepcionado. Le daremos otra oportunidad para decidir si lo incluimos entre los frameworks de prueba en Learning Project.

 

Documentación utilizada

  • Spring Roo Project: página principal del proyecto, desde aquí puedes acceder a toda la documentación (inglés).
  • Spring Roo and JPA Entities: explicación y aclaración de las relaciones entre entidades en Spring Roo (inglés).
  • Apache Maven
  • Maven in five minutes: por si no tienes ningún conocimiento sobre Maven, aquí tienes una introducción básica.
  • Para preguntas sobre Spring Roo podemos usar StackOverflow , donde nos ayudarán a resolver nuestras dudas y ayudr con ello a conocer mejor la herramienta.
  • Complementos (add-ons): añado el interesante enlace que me aportan en los comentarios sobre un add-on suite que parece muy interesante para el desarrollo con Spring Roo: gvNIX. Incluye funcionalidades como integración con jQuery, Bootstrap, Dandelion-datatables, Auditoria con Histórico de cambios, Jasper Reports… aporte por Jose Manuel Vivó Arnal

 

Espero que te haya sido útilXules

Let’s do some initial tests with Spring Roo Project to see if we include it in the project development environments Learning Project. To make a development as quickly as possible and make an assessment we will use a single table from those reflected in the draft here you have all the information.

Spring Roo

A next-generation rapid application development tool for Java developers. With Roo you can easily build full Java applications in minutes.Spring Roo

Ultimately we will see that we can generate CRUD application with Spring Roo for the customerdbroo database where we will create the cb_language table with the following database structure:

Esquema de la tabla cb_language

Esquema de la tabla cb_language

cb_language

Table with the languages on the application, it could be related to multiple tables.

In this tutorial we will learn to make a Web application from scratch using Spring Roo, what we do:

Spring Roo characteristics

Spring Roo is presented as a lightweight tool to more quickly achieve instant results, we will see if they are suited to our basic needs, the generated code is Java so we understand that we can customize the generated code, we’ll check it.
Spring Roo aims to to differentiate from other tools by::

  • Rapid results
  • 100% develop in Java
  • Easy-to-use
  • Fast and simple to remove
  • Totally compromise free
  • Active, helpful community
  • Comprehensive technology integrations
  • Extension points via Roo add-ons
  • Spring-certified architecture

 

Prepare the enviroment

For these tests we will work with the environment provided by Spring Tool Suite (STS), here you can download the version you need for your operating system, Spring Tool Suite (STS) provides support for Spring Roo 2.0.0 is available from STS 3.7.0, in the download link you will found all the information.

Now we are going to include Roo in our STS IDE:

  • Open your STS IDE
  • Open the STS dashboard
  • Click on Extensions bottom tab and search Spring Roo.
  • Install Spring IDE – Roo Extension.
  • Restart STS

Configuring Spring Roo 2.0.0 in your STS:

  • Open «Preferences > Spring > Roo Support»
  • On «Roo Support» we click the «Add» button for the installation
  • In «Roo Configure Roo Installation» click the «Browse» button, then select the directory where you unzipped Spring Roo 2.0.0
  • Confirm the installation
  • Now Roo is installed on your STS IDE

With this we let our IDE configurated to use Spring Roo.

Now we just need to install PostgreSQL on our computer if we have not already installed, in the post PostgreSQL Tutorial (1): Setting the environment have all the necessary information and links for downloading and basic configuration.

 

Project creation and configuration

With the IDE STS now ready for Spring Roo, let’s create the project, for this we go to the dashboard where we find the option : Spring Roo Project that allow us to generate a Spring Roo project as you can see in the picture:

Spring Roo Project Creation

Spring Roo Project Creation

Now on the create screen we fill again the information requested as show in the picture and click next button:

Spring Roo New Project Creation

Spring Roo New Project Creation

Once we made the selection the following message appears on screen: «Please click ‘Finish’ to create the new project using Roo», and we will only have to press the button FINISH. Now we have our project created and the Spring Roo console will use to create the persistence unit, the tables, and MVC web project genearation, then we will explain its use by using it, in the picture you can see the project and the console will use.

We are going to perform our setup with PostgreSQL database that we are going to create and call customerdbroo.

jpa setup --provider HIBERNATE --database POSTGRES --databaseName customerdbroo

 
When we run this on the Roo console shows the actions performed, remember to refresh the project to reload the new files created:

Spring Roo Project - Roo databse configuration

Spring Roo Project – Roo databse configuration

As you can see in the picture the files have been created: the files of the application,the application settings, persistence and let’s modify now database.properties where we complete the username and password to access the database, and finally will:

#Updated at Wed Nov 04 23:04:43 CET 2015
#Wed Nov 04 23:04:43 CET 2015
database.driverClassName=org.postgresql.Driver
database.url=jdbc\:postgresql\://localhost\:5432/customerdbroo
database.username=xulescode
database.password=xulescode

I recommend you to explore the files created to become familiar with the environment, but for now the only file you have to modify is what we have set.
 

Creating the entity for cb_language

Now we can create our domain objects and the fields which we are going to define our class to cb_language. Now we will use the entity jpa command to create our entity, this command has a set of attributes which we will use:

  • class that allows us to specify the domain, and then, and then, when we create the other tables, or later, when we want to add new fiels will allows us to specify what entity we are modifying.
  • testAutomatically attribute that creates the integration test for a domain object.

Once it was clear this we will create the entity CbLanguage running on the Roo console :

entity jpa --class ~.domain.CbLanguage --testAutomatically

 
Remember to refresh the project to see actions done, these are shown on the consolo as follows:

roo> entity jpa --class ~.domain.CbLanguage --testAutomatically
Created SRC_MAIN_JAVA/org/xulescode/mode/domain
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage.java
Created SRC_TEST_JAVA/org/xulescode/mode/domain
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand.java
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest.java
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Configurable.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_Entity.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_ActiveRecord.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_ToString.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_DataOnDemand.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest_Roo_IntegrationTest.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageIntegrationTest_Roo_Configurable.aj
Created SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_Configurable.aj

 
Now let’s add the fields, first we’ll add is idlanguage that according to the structure initially defined for the table should be the primary key, in this first approach to Spring Roo have not found a way to indicate that I want this to be the primary key with this name in the end we will see why this happens and what is the primary key that automatically generates us Spring Roo. To add a new field the structure is simple use the command field followed by the data type and now we can use some attributes, this link have more attributes available, we use here are:

  • –fieldName idlanguage indicates the field name
  • –notNull we indicate that the field can not be NULL.
  • –sizeMax 6 indicate the maximum size, we can also indicate the minimum with sizeMin
  • –class ~.domain.CbLanguage as I said earlier we used to indicate that domain we are working, we now really do not need because we are working within the domain CbLanguage

Thus creating our first field looks like this:

field string --fieldName idlanguage --notNull --sizeMax 6 --class ~.domain.CbLanguage

 
This is the result shown on our console for our first field, I indicated simply to take notice that you now are working on the console with the domain CbLanguage (~.domain.CbLanguage roo>):

~.domain.CbLanguage roo> field string --fieldName idlanguage --notNull --sizeMax 6 --class ~.domain.CbLanguage
Updated SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage.java
Updated SRC_TEST_JAVA/org/xulescode/mode/domain/CbLanguageDataOnDemand_Roo_DataOnDemand.aj
Updated SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_Jpa_ActiveRecord.aj
Created SRC_MAIN_JAVA/org/xulescode/mode/domain/CbLanguage_Roo_JavaBean.aj

We add the remaining fields without much further for now:

field string --fieldName namelanguage --notNull --sizeMax 60 --unique 
field string --fieldName isactive --notNull --sizeMax 1 --value "N"
field string --fieldName languageiso --sizeMax 2 
field string --fieldName countrycode --sizeMax 2 
field string --fieldName isbaselanguage --notNull --sizeMax 1  --value "N"

 
This is the result of the fields that we have created in CbLanguage:

package org.xulescode.mode.domain;
import org.springframework.roo.addon.javabean.annotations.RooJavaBean;
import org.springframework.roo.addon.javabean.annotations.RooToString;
import org.springframework.roo.addon.jpa.annotations.activerecord.RooJpaActiveRecord;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.persistence.Column;
import org.springframework.beans.factory.annotation.Value;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class CbLanguage {

    /**
     */
    @NotNull
    @Size(max = 6)
    private String idlanguage;

    /**
     */
    @NotNull
    @Column(unique = true)
    @Size(max = 60)
    private String namelanguage;

    /**
     */
    @NotNull
    @Value("N")
    @Size(max = 1)
    private String isactive;

    /**
     */
    @Size(max = 2)
    private String languageiso;

    /**
     */
    @Size(max = 2)
    private String countrycode;

    /**
     */
    @NotNull
    @Value("N")
    @Size(max = 1)
    private String isbaselanguage;
}

Now we run the tests that we have automatically created with maven command perform tests, as explained in more detail in the section of the reference documentation. Using our STS we go to Run As > Maven test.

We can customize our Java code, if you want to see something else here’s an example: Edit, modify and customize the Roo-generated code, in this post will not enter into this section.

 

Resolving dependencies

Once finished this, and at least in my case, my project has errors in our file pom.xml, here was where i lost more time in the tutorial, until I noticed that there were configuration problems in the definitions used in the project, here are the fixes I have done to get things working properly.

		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
		<repository>
			<id>org.springframework.maven.release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://repo.springsource.org/libs-release-local</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>

 

MVC creation and configuration for web

Following project reference example of Spring Roo documentation, then generate the Web application that will manage the languages of the class CbLanguage, so for this we will run the web mvc command. First we will use web mvc setup to configure all the application controllers followed inmediately web mvc allcommand:

~.domain.CbLanguage roo> web mvc setup
~.domain.CbLanguage roo> web mvc all --package ~.web

 

Once finished, we have our application ready to run.

 

Project deployment and tests

Before running our project, placing us on the pom.xml file we run Run As >Maven install, once we have done it we must build our project, so, placing from the same place now run Run As >Maven build, and a menu will appear, like this:

Spring Roo Project Roo Maven package

Spring Roo Project Roo Maven package

We are using M2Eclipse that gives us integration to Apache Maven within the IDE, as shown in the photo are several options, in your case, It appears one without any definition, and this is because you have not yet set any goals , and selects one where it says Goals enter package, which is the command to compile our project.

Done this we are ready to run our project, stand over it and select Run As > Run on Server option, this is the result:

Spring Roo Project - Roo Web

Spring Roo Project – Roo Web

New language creation:

Spring Roo Project Roo Web Crear elemento

Spring Roo Project Roo Web Crear elemento

List of languages created for our entity CbLanguage, where we have the options of editing, viewing and deleting, completing our CRUD application.

Spring Roo Project Roo Web Listado de los elementos

Spring Roo Project Roo Web Listado de los elementos


 
As you can see the application is running and ready, with the setup we have each every time we run the project a new database will create, if we don’t want this simply we edit our persistence.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>
            <!-- Uncomment the following two properties for JBoss only -->
            <!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
            <!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
        </properties>
    </persistence-unit>
</persistence>

 

Here we modify the hibernate.hbm2ddl.auto property, and change it from create to update, so, we not delete the data every time they run the project.
 

Finished tutorial, these are my conclusions

  • Spring Roo is a powerful tool to build an application quickly as promising.
  • I do not like Spring Roo limitation when generating code for Roo console, for example, define your own primary key, I understand that you can do it, but subsequently modifying the Java code, I want to explore more about this, but it is the part I like least..
    • Correct my premature conclusion to point as indicated in a comment that we can identify our own primary key, and very easily, –identifierField idLanguage –identifierType java.lang.String, and already the primary key is generated.
    • field string --fieldName idlanguage --notNull --sizeMax 6 --identifierField idLanguage --identifierType java.lang.String --class ~.domain.CbLanguage
      
    • What I still is to convince all the generation in console Roo entities, this is a personal opinion since its functionality is there, strikes me or I like the option of reverse engineering, I will prove without doubt.
  • The initial generation of the web structure is quick and easy.
  • I do not like the limited possibilities that are introduced in the generation web mvc
    • Also correct conclusion is that not express exactly what I wanted, recently I worked with Openxava, where things are done differently, and I liked most (for now) its approach. To evaluate in the right measure Spring Roo I need to do more tests, and watch as more detailed add-ons that brings and if I find them very interesting.
    • Lo que te genera el Scaffold en una versión sencilla de lo mínimo necesario para la gestión de la entidad que has generado. Esto, por supuesto, es modificable y ampliable como tu creas necesario en tu proyecto. Además Spring Roo ofrece la posibilidad de automatizar operaciones generando complementos (add-on) que puedes instalar de forma fácil y sencilla gracias a los nuevos cambios introducidos en la versión 2.0 para su gestión y instalación como add-on suite contribution by Jose Manuel Vivó Arnal
  • The advantages of Spring Roo is full integration with Spring with what will easily be able to use Spring Security, for example, running the console: security setup.

Conclusion

In closing, I like the integration with Spring and tools, but does not convince me neither creating tables, neither the generation of the skeleton of the web, and I think that should provide more options, this is an initial conclusion and that the inclusion of Add-ons and the reverse engineering they could totally change my initial assessment.Xules

 
I still have pending try something more promising in relation to the database, because there is an option to reverse engineer our database already created, This option, if it works well, if I could cover my expectations created, and initially I’m a little disappointed. We will give another chance to decide if it is included among test frameworks in the Learning Project.

 

Documentation used

  • Spring Roo Project: Project home page, from here you can access all documentation.
  • Spring Roo and JPA Entities: explanation and clarification of the relationship between entities in Spring Roo.
  • Apache Maven
  • Maven in five minutes: if you have no knowledge of Maven, here’s a basic introduction.
  • For questions you can use StackOverflow Spring Roo, where they help us to solve our doubts and thereby help to better understand the tool
  • Add-ons: I add the interesting link that bring me in comments on an add-on suite that seem interesting development with Spring Roo: gvNIX. Incluye funcionalidades como integración con jQuery, Bootstrap, Dandelion-datatables, Auditoria con Histórico de cambios, Jasper Reports… contribution by Jose Manuel Vivó Arnal

 

I hope it has been useful for youXules