Using Spring Data JPA with a Liferay portlet

Technical Blogs November 10, 2015 By Matti Tahvonen

Service Builder is the way how developers are often encouraged to do DB connectivity with Liferay portlets. It is, though, by no means the one and only way how one can connect to databases from Liferay portlets. In many real world use cases, it is better to use standard JPA for ORM and access a DB that is separate from the DB used by Liferay for its internal stuff (such as user/role management). You portlet might be just one application using the DB and this way you can reuse the same JPA layer in other applications.

Spring Data is probably the best thing you can do to simplify your JPA data access code in general. I wouldn’t build even a trivial JPA based application without it (or its CDI “clone” called DeltaSpike Data). This tutorial gives you an overview of how you can use a modern JPA setup with Liferay portlets. It also introduces a simple method to combine data from your Spring Data repositories and Liferay’s user database - we’ll use email addresses as keys to identify the users in the external database.

In this example we’ll use Vaadin as a UI framework, but the real meat of this article should be easily adaptable to other UI setups as well.

Basis: Spring context and Spring Boot

To startup with any Spring application, we need the core (the IoC container) to be bootstrapped. In this example, we’ll use Spring Boot. Even though we cannot use all of its features in portal environment(namely jar packaging), its convention over configuration features will greatly simplify setting up Spring Data (connecting to the database, connection pooling, setting up persistence context etc).

To get started with Spring Boot, add the following parent to your portlets pom.xml file:


The basic dependencies are the same as for typical web apps, but we should exclude tomcat related stuff: org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat

Vaadin Spring doesn’t yet support portlets out of the box, but luckily there is an awesome community that shares their helpers. The popular Vaadin4Spring contains a module that can be used to setup portlet support for Vaadin Spring portlets:


In addition to the dependency, we’ll need to specify that we use SpringAwareVaadinPortlet instead of raw VaadinLiferayPortlet class in portlet.xml file:


As a final step, we’ll introduce a similar Spring configuration class as we’d do with a basic (war packaged) Spring Boot app.

public class ApplicationConfiguration extends SpringBootServletInitializer {

    static class ApplicationProperties {

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ApplicationConfiguration.class);

Finally just annotate your Vaadin UI class with @VaadinPortletUI annotation (from vaadin4spring module) and your object becomes a Spring managed bean: @VaadinPortletUI public class LibraryPortletUI extends UI {

    ApplicationContext ctx;

    protected void init(VaadinRequest request) {
        setContent(new Label("I'm a Spring managed bean in " 
            + ctx.getApplicationName()));


Setting up Spring Data

Now that our app has a Spring Boot based Spring context ready, setting up Spring Data and JPA stuff becomes really simple. Just adding @EnableJpaRepositories annotation to your configuration class and adding org.springframework.boot:spring-boot-starter-data-jpa dependency is enough to get started. This brings in both JPA implementation (Hibernate by default) and various Spring Data related JPA tools. Thanks to Spring Boot, the example automatically uses H2 in memory database, just based on the fact that it finds H2 database from the classpath. When going to production, you might want to add another DB driver to your classpath and configure the DB url in file to point to your own database.

Note, if you are not ready to go with Spring Boot, setting up the basis for Spring Data is slightly more tricky but still perfectly possible. I suggest to follow these sharp instructions which apply for portal environment as well.

In our example we have only one entity, Book, that is declared like this:

public class Book extends AbstractEntity {

    private Date publishDate;

    @NotNull(message = "Name is required")
    @Size(min = 3, max = 50, message = "name must be longer than 3 and less than 40 characters")
    private String name;

    private String description;

    private String borrowedBy;

    // getters/setters not listed 

The superclass, AbstractEntity, just contains basic primary key declarations and often needed proper equals/hashcode implementations.

The basic Spring Data repository for the Book entity can be declared like below. This simple declaration already introduces most methods needed for simple CRUD applications, by inheriting them from the super interfaces.

public interface BookRepository extends JpaRepository<Book, Long> {


In a real world use case, you’ll probably want to throw in some domain specific methods, for example, by simply relying on the handy method naming conventions. Spring Data could, for example, implement a method like public List findByEmail(); automatically, without any fiddling with EntityManager or JPQL queries. If you are new to Spring Data, refer to the excellent Spring Data tutorial to get an overview of how powerful a repository pattern can be.

Tie pieces together

At this point we have already made our UI objects Spring managed beans and introduced a repository class to access our entities. Instead of autowiring the repository directly to the UI code, we’ll introduce a service class specifically tailored for our UI code. In this case we’ll make the service UIScoped. This way it will be easier for us to integrate our Spring Data based DB with the user data coming from Liferay’s helper services.

Let’s start with the easy part, injecting in the repository and exposing a couple of trivial methods to our UI:

public class LibraryPortletUserService {

    private BookRepository repository;

    public void save(Book entity) {;

    public List<Book> findAll() {
        return repository.findAll();

To build integration with Liferay’s user data and our own database, we’ll need to get references to User and Company object. A simple way to find them is to use VaadinLiferayRequest that provides a current PortletRequest by a static helper method. The @PostConstruct method of the UIScoped bean is executed during an http request, so we can gain references to PortletRequest safely via helpers found from the VaadinLiferayRequest class.

private User currentUser;

private Company company;

public void init() {

private void initUserAndCompany() {
    try {
        currentUser = PortalUtil.getUser(VaadinLiferayRequest.getCurrentPortletRequest());
        company = PortalUtil.getCompany(VaadinLiferayRequest.getCurrentPortletRequest());
    } catch (PortalException e1) {
    } catch (SystemException e1) {

Now making that loose connection between Spring Data managed DB and portal user database becomes trivial, and most essentially, it becomes transparent to the UI code. An example of the borrowBook business method:

 * Sets the email field of the Book entity to current Liferay users
 * main email and persists changes to DB.
 * @param b the book to be set borrowed by current user
public void borrowBook(Book b) {

As the final step, we’ll simply use the @Autowired annotation to get a reference to the service in our UI code. E.g. listing entities in our UI becomes as simple as this:

LibraryPortletUserService service;

private MTable<Book> bookListing;

protected void init(VaadinRequest request) {

Trying it yourself

The full source code I used to write this introduction is available in github. The easiest way to try it is naturally just executing mvn install and deploying the war file to your Liferay portal. More than that, I suggest to install the full Liferay SDK, with proper Maven profiles, and play with your custom version locally.

Check out the example portlet from Github

Smoother Vaadin portlet initialisation - fix the height!

General Blogs October 30, 2015 By Matti Tahvonen

Vaadin portlets initialise using JS and XHRs, typically a couple of milliseconds later than basic html markup based portlets. This approach may cause “flickering”, which may be a bit disturbing if there is other content below the Vaadin portlet, because the browser needs to re-flow the whole page after the Vaadin UI has decided how much space it actually needs in vertical direction.

This feeling of slightly sluggish initialisation can be minimised by fixing the height of the portlet. Fixed height will let browsers make some optimisations (no full page reflow), but more essentially the rendering just feels smoother without the visible reflow. Fixing the portlet height also often makes UI design easier as one can use full height in the Vaadin UI code and user relative sizes to position and stretch components.

There are two good ways to fix the height:

  1. Using Liferay’s per portlet styling (or global theme) after the portlet has been installed on some page.
  2. A programmatic approach in your portlet code.

I favor the second one as it gives a good default for your portlet and requires less tricks from the actaul portal maintainer, who might be much less technical people than you are. Let’s see how this is done.

An initial idea for Vaadin developers would be to use your portlets theme to fix the height or call setHeight method for the UI class. The problem with these approaches is that the theme is also injected dynamically by bootstrap code (html+js) and the explicit size comes a bit too late with the initial XHR that contains the state of the UI. Neither would avoid the slight flickering. Instead we’ll use a concept called BootstrapListener to modify the bootstrap code that VaadinPortlet generates.

The BootstrapListener is attached per user, so we’ll use a SessionInitListener and hook that by introducing our own Portlet class:

public class MySpringVaadinPortlet extends SpringAwareVaadinPortlet {
    protected void portletInitialized() throws PortletException {
        // ... or modify the Vaadin generated bootstrap html/js code
        getService().addSessionInitListener(new SessionInitListener() {
            public void sessionInit(SessionInitEvent event) throws ServiceException {
                event.getSession().addBootstrapListener(new BootstrapListener() {
                    // The implementation...

As my app uses Spring, I’m extending the SpringAwareVaadinPortlet, but you can extend the raw VaadinPortlet class as well. To actually use the custom portlet, remember to modify the portlet class declaration in your portlet.xml file.

In my example I wrote the BootstrapListener rudely as an inner class to the portlet as follows:

public void modifyBootstrapPage(BootstrapPageResponse response) {
    // NOP This is used by servlets only
public void modifyBootstrapFragment(BootstrapFragmentResponse response) {
    Element styleElement = 
    String classname = 
            " { height:"+LibraryPortletUI.portletHeight+";}");
    response.getFragmentNodes().add(0, styleElement);

To generate (and customize) the bootstrap stuff, Vaadin uses the popular JSOUP library to handle the stuff. Refer to their documentation in case you want to do something fancier. We could, for example, get a similar result by just declaring the height to the first Node like this:

Node n = response.getFragmentNodes().get(0);

The former approach is a bit more elegant as it just defines a default height to our portlet, which can be easily overridden in the portlet’s own CSS declarations.

I hope your Vaadin portlets are smoother than ever after this pro tip!

Adapting Valo theme to fit the Liferay 6.2 defaults

General Blogs September 16, 2015 By Matti Tahvonen

The easily customizable, SASS based, Valo theme is one of the largest renewals to Vaadin lately. The vaadin-archetype-liferay-portlet still uses the oldish “liferay” theme, adapted for older versions of Liferay, but you can typically get much more appealing results with your Vaadin based portlets with the new Valo theme.

The customizability of Valo is based on certain parameters that SASS compilation uses to produce the CSS files served for the browser. Most notably there are a couple of “base parameters” that are used to calculate others. For example, if you change the $v-background-color variable to a dark tone, the theme will by default calculate, for example, the base font to be a light color to preserve a proper contrast. Just by modifying this one base color variable you can change the whole color theme of your application.

Valo parameters for Liferay look-alike theme

A Vaadin portlet themed with Valo that is adapted to Liferay 6.2 theme.

Valo, with its defaults, is already a pretty good fit into the default Liferay theme, but there are a couple of things we can tune to make it fit better. Although many Liferay users have their own totally customized themes, let’s look at how we can make a Valo theme variant that mimics the default Liferay 6.2 theme. Based on these tips you can probably fit it into your use cases as well.

  1. Change inheritance. If you created your Vaadin portlet with vaadin-archetype-liferay-portlet Maven archetype, there is already a SASS compilation setup and theme ready for you. The first thing to do is to make it inherit from Valo instead of the old “liferay” theme. Go to “mytheme.scss” file (or whatever your theme name is) and change all occurrences of  “liferay” to “valo”.

  2. Adjust fonts. Valo by default uses the Open Sans font, but we’ll just want to use what is defined by the Liferay theme. Also we’ll want to adjust the font-size to match perfectly with what the Liferay theme does. Add these to the top of your SCSS file:

    • $v-font-family: inherit;

    • $v-font-size: 15px;

  3. Adjust roundness and spacings. The Liferay default theme is actually quite similar to Valo in many areas, but it uses a bit less roundness in its components and a bit less “air” between various components. I used these variables to make the Vaadin part look almost identical with the default Liferay stuff:

    • $v-border-radius: 2px;

    • $v-unit-size: 30px;

    • $v-layout-spacing-horizontal: 15px;

    • $v-layout-spacing-vertical: 15px;

    • $v-layout-margin-right: 10px;

    • $v-layout-margin-left: 10px;

    • $v-layout-margin-top: 20px;

    • $v-layout-margin-bottom: 10px;

  4. Adjust colors. Also, the color theme is out of the box quite close to Valo. Someone with more eye for colors could probably adjust the $v-background-color variable to make it match even better, but I just decided to override the focus color to match with the one used by Liferay. In addition to focus outlines, this color affects some UI elements like the color of  “primary buttons”. Also, I overrided the background color of the “app pane” to be white (light gray by default in Valo).

    • $v-focus-color: #50a2f5;

    • $v-app-background-color: #ffffff;

  5. Some finetuning. At this point we are almost done. For my portlet, I still did two more small fine tunings. The captions in Liferay are no different from other texts, so I removed font-weight declaration defined by Valo. Also, I had to do a small trick to the text field height due to CSS rule collisions: Liferay applies size for all inputs and Vaadin defines the sizes using the “border-box” sizing method. These kind of rules are best placed inside your themes “mixin” part, so that they don’t leak into other Vaadin themes (in case you have two Vaadin portlets with different themes). “Web inspectors” in modern browsers are excellent tools to help define this kind of finetuning.

    • .v-caption  {
         font-weight: inherit;

    • .v-textfield {
         height: 30px !important;

These small variable definitions and special rules already give us a pretty nice fit into existing Liferay 6.2 based portlet themes, but there are probably a lot of small details that could improve the solution. If you want to join the effort, please send your pull requests to the dawn project. I added a “ray” theme to it that currently contains these basic rules. If we can make the “ray” theme more complete, let’s contribute it directly to the Vaadin project to replace the existing outdated “liferay” theme.

Vaadin 7.3 for Liferay released

General Blogs September 2, 2014 By Matti Tahvonen

As you might know Liferay comes bundled with Vaadin. Now that Vaadin 7.3 is out as of today, it is perfect time to update your Vaadin portlet. Vaadin 7.3 is the largest release since Vaadin 7 in February 2013. Its largest enhancement is a parameter driven look and feel, powered by Sass and CSS3. With just a few parameters you can completely change the look and feel from iOS6 round to Windows8 flat or anything at all. 

In Valo one parameter, such as the background colour, not only changes the background, but also derived colours in drop shadows and text colors so that as high usability as possible is achieved. Finally you don't need to be a skilled UI designer to design applications that always look beautiful. And, even with its default values, Valo fits alsmot perfectly into the default Liferay 6.2 theme and thanks to stronger selectors it has less conflicts than the old “Reindeer” theme. Thus, I like to say that Vaadin 7.3 is built for Liferay.

To keep working with Sass based themes as easy as possible, we even built our own Java-based Sass compiler that we have open sourced. It compiles the new theme about twice as fast as the original Ruby based compiler.

Try out Vaadin 7.3 today by updating your version to 7.3.0 in pom.xml of your self-contained Vaadin project or by updating your shared vaadin libraries to 7.3.0.

Check out the release post and the Valo page itself.


Vaadin + Liferay: a recognized combination

General Blogs August 26, 2014 By Matti Tahvonen

We were very happy to have received the Liferay Marketplace award for the best Free Opensource portlet for 2014 . This was a huge thing for us not only because itself uses the Tori forum portlet as its main discussion board, but also because Tori has shown us how awesome a combination Vaadin and Liferay really are together!

With the help of Vaadin you're able to build real Business Applications (with a capital A) and Liferay gives a solid ground for Vaadin applications to lean on.

A while ago we had a joint webinar about Vaadin & Liferay together, but received lots of questions on a more detailed Vaadin introduction to those of you not familiar with Vaadin from before.

Good news: We're hosting an Introduction to Vaadin Webinar already next week that will make you familiar with Vaadin in 30 minutes. Join Vaadin founder Joonas Lehtinen for an introduction and with answers to your questions on Thursday September 4th  @ 10AM PT (1PM ET). Sign up now at and learn to make your own Tori or larger business apps with Liferay and Vaadin!

Vaadin Joins Portlet Specification Standard 3.0 group

General Blogs June 26, 2014 By Matti Tahvonen

As you probably know Liferay comes packaged with Vaadin and many portal developers are using Vaadin as their UI library for building rich web applications. Vaadin has been a good choice for those that want something more than just JSF with a little JavaScript sprinkled on the top but at the same time the current Portlet specification wasn't really made for full-RIA such as the ones written in Vaadin. 

Portlet Standard 3.0 tends to fix this and we are proud to be a part of it as well. Vaadin just joined the JSR-362 specification group with its aim to ease AJAX communication, specify how portlets share resources and add websocket support. Something we at Vaadin have been doing for the past 13 years already. 

The group itself is very strong with Neil Griffin from Liferay participating and IBM's Martin Scott Nicklous leading the JSR. We hope to bring some insights into the group and hopefully ease the development of Liferay+Vaadin applications with the help of the next standard. Because of this, we'd love to hear from you as well. What has been the largest hindrance for you and is there something the specification could tackle already? Just leave a comment below!

For more information see the JSR site: or the Vaadin Press Release

Using "self-contained" approach to package Vaadin portlets

General Blogs May 23, 2014 By Matti Tahvonen

As you might know, Vaadin libraries are bundled in Liferay. This makes it easy to start developing basic Vaadin portlets and you’ll also save in war file size as you are sharing the libraries between your projects. There are also a couple of global Liferay configuration properties (like vaadin.theme) that affect all Vaadin projects deployed on Liferay.

The approach currently used by most tools has some inconveniences though. Practically all your portlet projecs have to use same version of Vaadin and share the set of Vaadin add-ons. When you update one Vaadin portlet, all others should follow.

As a new default way of packaging your Vaadin portlets, you should start using a “self-contained” approach instead. We discussed this yesterday in our joint webinar by James Falkner and Mac Przepióra. In this packaging style each project has its own Vaadin libraries and generated resources packaged into its war file. In addition, each project can configure itself independently of to another and of the global configuration in Now adding add-ons to a project is as easy as in servlet based Vaadin apps and there is a new Vaadin version available, all projects don’t need to be updated at once.

As a downside, the war file size grows a bit and a page with multiple Vaadin portlets from different projects might become slightly slower to load. In case you have lots of small Vaadin portlets, from different portlet projects, and it is essential to optimize the page well, then, and only then, I can still suggest to use the shared library packaging.

The new packaging style is available as a Maven archetype. To prepare for using Liferay IDE with Maven, you’ll need to add a “liferay” profile to your settings.xml For more information about using Maven with Liferay IDE, you can refer to Liferay documentation.

This is the profile I have in mine:



The archetype can be found from Maven central with groupId com.vaadin and artifactId vaadin-archetype-liferay-portlet. If you create a project with Eclipse and Liferay IDE, the next step is to configure the project using the previously discussed profile via project properties. Screenshot below shows where to do that.

After that the project should compile fine and Liferay IDE will recognize the project as a Liferay project (so you can also use Liferay Maven plugin goals like liferay:deploy and can edit Liferay deployment files like using Liferay IDE’s graphical forms-based editors).

Relevant Maven build targets:

install will package the project as war under target directory. If a widgetset has changed, this also activates the GWT compiler to build a new widgetset, so it might take a minute or two. E.g. if you add an add-on, like Vaadin Charts, execute this goal after modifying your pom.xml.

liferay:deploy will deploy the war to the liferay instance defined in your settings.xml

clean removes all generated resources like class files and widgetsets.

In case you wish to activate liferay:deploy during install target, you might also wish to configure liferay-maven-plugin with the following configuration.


We’ll most likely change the non-Maven builds to guide towards this kind of packaging style in the near future. Until then, and in case for some reason you cannot start to use Maven builds for your projects, you can create a one project stub using the archetype and then adapt that for your ANT build. I haven’t tried it but I think it should work as well.

The good thing about Maven builds is that it hints your IDE how it should configure the project. If your colleague is a big fan of some other IDE, he can probably just open the project in his IDE and start working. I tested this with NetBeans and it worked flawlessly, and I’d be surprised if it didn’t work in IntelliJ IDEA as well.

Migrating to Vaadin 7

In this post we assume you are using Vaadin 7, but the latest version of Liferay (6.2) includes an older version of Vaadin (Vaadin 6). This isn’t a problem if you use the new vaadin-archetype-liferay-portlet and per-project approach as outlined above. However, if you have many projects that use Vaadin and are looking to optimize your production environment (to minimize the duplication of runtime classes and widgetsets between projects and tosave on JVM resources), you may want to use a single version of Vaadin across all projects (the “global” approach), which requires upgrading the bundled version of Vaadin (6.8) to whatever version you wish to use.

In addition, we are working with Liferay to update the Liferay IDE plugin to support not only creating new Vaadin 7 projects. In the future, new projects should be created in a form of “self-contained” strategy by default, whether they used Maven or not.

Showing 7 results.
Items 20
of 1