Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
Former Member

SAP HANA is a rather interesting, efficient in-memory database. It can be purchased as a “black box” server (rented hardware, with pre-installed software) that you place to your server room or simply use as a cloud service. Together with the actual RDBMS, you can use SAP HANA Cloud Platform execution environments to host your business apps.

Vaadin is a powerful UI framework that you can easily use together with SAP HANA Cloud Platform (HCP). With it, you’ll most often be working with plain Java and can completely forget that you are building a complex modern web application. The programming model is quite similar to Java Swing, the UI logic lives securely on the server’s JVM and in the browser, there is only a small auto-generated thin client that communicates securely and efficiently with the server. And it’s opensource and free to use, under the Apache 2 license.

There are lots of different kinds of applications, that all have their custom requirements, but for most business apps, Vaadin is an excellent alternative to a client side development model, such as SAPUI5. The performance boost that you, as a developer, will gain from the pure Java/JVM approach of Vaadin is unparalleled.

Let’s have a look at how you can set up a SAP HANA Cloud Platform application, with a Vaadin based UI, that you execute in the HCP. I’m also covering a bit of some best practices for project setup and JPA usage, which might be interesting, even if you’re using or planning to use something else besides Vaadin.

Setting up a SAP HANA Cloud Platform development environment

Once you have downloaded the development package, you could check out the bundled examples. I derived this example from the official persistence-with-ejb example which provides a solid basis for your application. In the project setup, there is something that I’d do a bit differently though. Emphasizing Maven conventions and a bit stronger modularization will probably save a lot of time in the future.

The first thing I suggest to do when starting with HCP development is to create a Maven profile to store some common properties in. In the default examples, this is dealt with a parent project, but this is probably more handy if you have lots of small HCP projects. An example of such a profile definition is found in the project’s readme-file. You should replace the path to the SDK with the one in your environment and replace the defaults with your own username-password combination.

Our final project will be split into a backend and a UI module, both built by the master project. To the backend module, I’m placing all JPA stuff and the EJB via entities that should be fetched and updated. This part of the application is pretty much the same (~ 100% re-usable), whether you’re  building your application with Vaadin, any other UI technology or if you’re just publishing REST services for third party developers.

The UI module is a rather standard Java web application project, building a war file suitable for Java EE 6 execution environment. You could naturally combine all stuff (JPA model, EJB, Vaadin UI) to a project creating just one war file, but splitting your app into modules will help you to structure the re-usable parts better and helps to spread the effort to a larger team.

The folder structure for the final project looks like this (simplified):

project-root/
    pom.xml
    hana-backend/
        pom.xml
        src/...
    vaadin-ui/
        pom.xml
        src/....

The backend module

The JPA model for the example is a bit like the official SAP EJB persistency example, but I wanted it to be a bit more advanced. I added another JPA entity, Team, to which there is a relation from the Person object. I also extracted an abstract super class for entities. To the AbstractEntity, I placed things like identifiers, hashCode, equals methods and timestamps, like created and lastModified. The superclass helps to avoid lots of boilerplate that’d need to be written to pretty much each and every entity.

This is what the AbstractEntity looks like:


@MappedSuperclass
public class AbstractEntity {
    @Id
    private String id;
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModified;
    public AbstractEntity() {
        this.id = UUID.randomUUID().toString();
    }
    // getters and setters are omitted
    @PrePersist
    public void onPrePersist() {
        created = lastModified = new Date();
    }
    @PreUpdate
    public void onPreUpdate() {
        lastModified = new Date();
    }
    @Override
    public int hashCode() {
        return id.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof AbstractEntity)) {
            return false;
        }
        return getId().equals(((AbstractEntity) obj).getId());
    }
}



The actual entities (Person and Team) then become quite a bit simpler. The Team entity, with its one and only property, looks like this:



@Entity
@Table(name = "T_TEAMS")
public class Team extends AbstractEntity {
    private String teamName;
    public String getTeamName() {
        return teamName;
    }
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
    @Override
    public String toString() {
        return teamName;
    }
}



Although many J2EE veterans have a healthy allergy for EJBs, since Java EE 6 there are no excuses why you shouldn’t hide your JPA related code to an EJB. Stateless local EJB makes your code simpler, easier to write and maintain and it will also perform extremely well. If you write your DAO’s as EJB’s, you can, for example, forget transaction management most of the time as the container will intercept our service methods automatically.

Writing your JPA code to an EJB based service also gives you a nice separated module that you can re-use in many different applications, whether you were building rich web UI’s with Vaadin or low level REST services for third party application developers. The PersistenceFacade in my example, with one business method, is as simple as this:


@Stateless
@LocalBean
public class PersistenceFacade {
    @PersistenceContext
    private EntityManager em;
    public List<Person> getAllPersons() {
        return em.createQuery("select p from Person p", Person.class).getResultList();
    }



I added the very simple JPQL example in the above, but most often I don’t suggest JPQL or Criteria API to access your JPA entities. I recently wrote an article series of three excellent JPA libraries, Spring Data, DeltaSpike Data and QueryDSL, that will help you to write queries in a more efficient manner. In this example, I used QueryDSL to write methods to e.g. filter Person entities with a string filter:



public List<Person> getPersonsMatching(String filter) {
    JPAQuery query = new JPAQuery(em);
    QPerson p = QPerson.person;
    List<Person> list = query.from(p)
            .where(
                    p.firstName.containsIgnoreCase(filter)
                    .or(p.lastName.containsIgnoreCase(filter)
            )).list(p);
    return list;
}



The QPerson class in the above code snippet is a helper class, automatically generated by QueryDSL, based on the JPA entities. This way QueryDSL allows you to write the queries with a well typed Java API. The advanced Java IDEs will then help you to write your queries so that they actually work on the first run, which is not that common with raw JPQL or SQL. 😉

The UI module

Vaadin UI modules are basically WAR files and are executed as a servlet behind the scenes. In the project’s pom.xml we add a dependency to our hana-backend module, so that the EJB containing the business logic is included in the produced WAR file.

Normally I’d strongly suggest to use Vaadin CDI to make UI classes CDI managed bean. CDI is kind of the glue that you can use to put together your well modularized Java EE services. As there are still some rough edges in the provided Java EE container, CDI support doesn’t fully work in all situations in the HCP.

The issue in the container is probably fixed pretty soon, but even without Vaadin CDI, it is still rather easy to use Vaadin in SAP HANA Cloud Platform. We can just use Servlet 3 style annotations to declare the servlet instance and injecting the EJB there works well. To actually use the EJB from Vaadin classes, I created a small static helper method (based on a “thread local” variable) to get access to the EJB from anywhere in the Vaadin code.


    @WebServlet(urlPatterns = "/*", name = "HanaUIServlet")
    @VaadinServletConfiguration(ui = HanaUI.class, productionMode = false)
    public static class HanaUIServlet extends VaadinServlet {
        @EJB
        private PersistenceFacade personBean;
        public PersistenceFacade getPersistenceFacade() {
            return personBean;
        }
    }
    public static PersistenceFacade getPersonBean() {
        return ((HanaUIServlet) VaadinServlet.getCurrent()).getPersistenceFacade();
    }

The hard part is now done. The rest is just simple component based UI development. If you have been building e.g. Swing based desktop applications before, you’ll really see the similarities with Vaadin immediately. The heart of this demo UI is the listing of Person entities to a table component in the UI (see HanaUI class) and the reusable PersonForm component that lets users edit the Person entities. The table is initialized like this:



MTable<Person> personList = new MTable<Person>(Person.class).withProperties(
        "firstName", "lastName", "created", "lastModified");



In the init method, we populate the list like this:



personList.setBeans(getPersonBean().getAllPersons());



I’m using a Viritin helper library that provides some enhancements to the core Vaadin components. You can naturally do this with the core components or application specific helpers as well, but I like to emphasize the modularity that the Java ecosystem and Vaadin tackle so well. As you progress with Vaadin, you’ll probably want to do some domain specific libraries for yourself too. There are more than 500 different extensions and helpers available for Vaadin via  Vaadin Directory today. If you think something might be missing from Vaadin, first check out the Directory.

There is also a typical UI to filter the person listing. The filtering is implemented with a TextField and a TextChangeListener, and the code shows how simple building UIs with Vaadin can be. Once the user types in and keeps a tiny pause, the client sends a tiny request to the server that initiates the following TextChangeListener, where we’ll create a filtered query to the backend and bind only the relevant rows to the table.


search.addTextChangeListener(new TextChangeListener() {
    @Override
    public void textChange(TextChangeEvent event) {
        String text = event.getText();
        if (StringUtils.isNotEmpty(text)) {
            filterEntities(text);
        } else {
            // empty filter, list all
            listEntities();
        }
    }
});


In the filterEntities method, we simply use the business method we built using QueryDSL in the previous chapter.

Getting forward with SAP HANA Cloud Platform and Vaadin

If you look at the full HanaUI class and composites like TeamSelect and the PersonForm class, you’ll get a pretty good picture of what Vaadin development is like. In a larger project, you’ll naturally have concerns like navigation and view management that you’ll want to tackle. To get examples and ideas of how to build your larger Vaadin application, check out the Book of Vaadin, join a local Vaadin meetup group or training and search for Vaadin examples in GitHub!

Source code for the SAP HANA Cloud Platform + Vaadin example

16 Comments
Labels in this area