Spring Roo basic example with PostgreSQL

Proyecto Spring Roo con PostgreSQL en 6 pasos

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


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

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;

public class CbLanguage {

    @Size(max = 6)
    private String idlanguage;

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

    @Size(max = 1)
    private String isactive;

    @Size(max = 2)
    private String languageiso;

    @Size(max = 2)
    private String countrycode;

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

			<name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
			<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
			<name>Spring Maven Release Repository</name>


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">
            <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" /-->


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.


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

5 responses on “Spring Roo basic example with PostgreSQL

  1. Jose Manuel Vivó Arnal

    Hola Xules,

    Primero, felicitarte por tu magnifico Post. Siempre se agradece encontrar guías como esta que pueden ayudar a la gente a mejorar su forma de trabajar.

    Me gustaría hacerte unos pequeños apuntes que pueden ser complementarios y que, además, pueden resolver algunas dudas que te aparecen:

    Identificador de la entidad
    Sobre la configuración de la claves primaria de las entidades: en la documentación de referencia puedes encontrar las opciones que ofrece el comando –identifier* que te permite gestionar este aspecto de la entidad. Por ejemplo, para generar el idLanguage como identificador de tipo String simplemente usa el comando:

    entity jpa --class ~.domain.CbLanguage --testAutomatically --identifierField idLanguage --identifierType java.lang.String

    Esto te creará la clase de la entidad así:

    @RooJpaActiveRecord(identifierField = "idLanguage", identifierType = String.class)
    public class CbLanguage {

    Lo que puede desconcertar es que la propiedad idLanguage se genera dentro del fichero CbLanguage_Roo_Jpa_Entity.aj y no en la propia clase, pero el resultado es el mismo y siempre puedes hacer un Refactor / push-in (más información sobre esto aquí) para incluirlo en la clase original (a partir de ese momento Spring Roo deja en tus manos la gestión de la propiedad) y así poderle añadir la notación para validar su tamaño (@Size).

    Resolviendo dependencias
    Lo que comentas en este apartado es bastante extraño ya que, en teoría, las dependencias de Spring Roo están accesibles desde los repositorios estándar de Maven (como puedes ver aquí).
    Si quieres, crea una consulta en StackOverflow con más datos y estaremos encantados de ayudarte.

    La capa Web
    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

    Complementos (add-ons)
    Sobre los add-ons quería añadir un enlace a un add-on suite que creo que os puede ser 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…

    Para terminar, animarte a ti y a cualquiera que tenga preguntas sobre Spring Roo a usar StackOverflow ya que nos permitirá compartir mejor el conocimiento de esta herramienta.

    Un saludo,

  2. Julio Yáñez Novo

    Hola Chema.

    Muchas gracias por tu aporte, esto es exactamente, lo que estoy buscando yo con la publicación de estos tutoriales, con tu explicación sobre la posibilidad de incluir idlanguage como clave, modifica y mucho mis conclusiones, y me dispongo a incluir Spring Roo dentro de mi proyecto Learning Project, para el desarrollo entero de una aplicación, y así poder comparar Spring Roo con OpenXava, JSF-Primefaces, y otros, futuros desarrollos.

    Lo antes posible modificaré esta publicación para incluir tu aporte.

    Resolviendo dependencias

    Al final me decidí a incluirlo en mi introducción, por si a alguien le pasaba lo mismo, lo analizaré otra vez antes de incluir la incidencia en StackOverflow.

    Complementos add-ons

    Me parecen muy interesantes y es algo que hecho de menos en otros frameworks Java.

    Como te decía, me has convencido para desarrollar el tutorial entero para obtener una aplicación funcional como la que he desarrollado para Openxava.



  3. Sin Nombre

    Gracias por el aporte.
    Muy buena documentación inicial.

    Estoy adentrandome en este mundo porque me parece muy interesante.
    Tengo una duda sobre si usar MySQL Server o PostgreSQL.

    ¿ Cúal es la diferencia ?
    ¿ Puedo tener ambos instalado sin tener problemas de conflictos de puertos u otros ?
    Anteriormente para realizar otras actividades relacionadas con PHP , instalé WAMP server
    ¿ Puedo utilizar algo de WAMP server para estos menesteres ?
    – Te lo comento porque no se a quién preguntar , que conozca este tema.

    Gracias por tu atención y trabajo.

    1. Julio Yáñez Novo Post author

      Muy buenas, respondo a tus preguntas:

      Tengo una duda sobre si usar MySQL Server o PostgreSQL.

      Puedes usar cualquiera de las dos bases de datos, dependiendo del proyecto te aconsejaría una u otra (mi preferencia es PostgreSQL), si conoces MySQL te aconsejaría que usarás está para facilitar tu aprendizaje, de todas formas si quieres aprender PostgreSQL está es una buena oportunidad, aquí te explico como instalarlo y utilizarlo, también, puedes encontrar el desarrollo de la base de datos que utilizo Customerdb en SQL: Tutorial PosgreSQL (1): Preparando el entorno.

      ¿ Cúal es la diferencia ?

      Ambas son bases de datos relacionales que difieren en su implementación y en la forma de almacenamiento de las tablas en las bases de datos, también encontrarás diferencias en su implementación SQL, esta es una explicación muy resumida. MySQL ha llevado el liderazgo en la web en implementaciones de blogs (WordPress, Joomla,…) y ecommerce (Prestashop,…), PostgreSQL no es tan utilizado en estos entornos, pero si en el desarrollo de aplicaciones empresariales ya que su respuesta, fiabilidad, y el funcionamiento de los procesos almacenados hace que sea un competidor de Oracle, encontrarás, por ejemplo, que muchos ERP están utilizando PostgreSQL.

      ¿ Puedo tener ambos instalado sin tener problemas de conflictos de puertos u otros ?

      Puedes instalar ambas bases de datos al mismo tiempo, solo dependerá de los recursos de tu equipo, por defecto, PostgreSQL se instala en el puerto 5432 y MySQL en el puerto 3306, en ambas este es un parámetro configurable.

      ¿ Puedo utilizar algo de WAMP server para estos menesteres ?

      No, necesitas un servidor de aplicaciones Java como Apache o Pivotal que es el que trae por defecto STS (Spring Tool Suite) que es el IDE que te aconsejo que utilices para desarrollar con Spring Roo.
      Apache o Pivotal son implementaciones de software open source de Java Servlet, JavaServer Pages, Java Expression Language y las tecnologías Java WebSocket, en esta publicación: Añadiendo Apache Tomcat a Spring Tool Suite, donde explico como instalar Apache Tomcat en STS puedes encontrar información sobre este servidor.

      Espero que mis respuestas te ayuden en tu elección. Saludos.

      1. Sin Nombre

        1 millón de gracias por la respuesta.
        A voz de pronto , tengo configurado en el IDE Eclipse , el plugin STS , Spring Roo , un servidor Apache Tomcat 8.0 , Maven2 , además añadí el gvNiX a la consola del IDE , lo tengo todo listo para empezar a trabajar , mi duda era sobre que sistema de base de datos usar y si podía ocurrir algún problema por usar ambas bd por si necesitaba seguir un ejemplo o hacer alguna prueba con una u otra.

        Una vez más gracias por su atención y paciencia.
        Todo lo que usted me ofrezca será bien acogido.

Leave a Reply

Your email address will not be published. Required fields are marked *