Skip to Content

End-to-End Weather App Scenario Part 7

By akula86

Enhancing the persistence layer for multi-tenency

You will learn

In this tutorial you will enhance the persistence layer with a multi-tenancy feature so that each user will be able to store their own favorite list.


  1. First, we’ll add the necessary annotations to the persistence BaseObject class. Open it and add the following two annotations to the class definition:

    @TenantDiscriminatorColumn(name = "TENANT_ID", contextProperty="")
    public abstract class BaseObject
    Adding Java annotations to a Java Class
  2. Next, we need to slightly adjust the way we obtain a reference to the EntityManager within the FavoriteCityService class as we now need to pass the current tenant ID (in our case the user ID). The following code snippet illustrates the concept:

    public List<FavoriteCity> getFavoriteCities(@Context SecurityContext ctx)
    List<FavoriteCity> retVal = null;
    String userName = (ctx.getUserPrincipal() != null) ? ctx.getUserPrincipal().getName() : "anonymous";
    Map<String,String> props = new HashMap<String,String>();
    props.put("", userName);
    EntityManager em = this.getEntityManagerFactory().createEntityManager(props);
    retVal = em.createNamedQuery("FavoriteCities").getResultList();
    return retVal;
    Modifying Java methods to handle the tenant ID
  3. Make your changes to the methods (getFavoriteCity(), addFavoriteCity() and removeFavoriteCity() ) in the FavoriteCityService respectively and save all edits.

    Modifying Java methods to handle the tenant ID
  4. Deploy/publish your changes. Please explicitly stop and start the server, as you have updated the persistence model!

Next Steps

Updated 12/22/2016

Time to Complete

10 min



Back to top