Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Jakarta EE: Multitenancy with JPA on WildFly, Part 1

June 15, 2020
Rhuan Rocha
Related topics:
JavaContainersDevOps

Share:

    In this two-part series, I demonstrate two approaches to multitenancy with the Jakarta Persistence API (JPA) running on WildFly. In the first half of this series, you will learn how to implement multitenancy using a database. In the second half, I will introduce you to multitenancy using a schema. I based both examples on JPA and Hibernate.

    Because I have focused on implementation examples, I won't go deeply into the details of multitenancy, though I will start with a brief overview. Note, too, that I assume you are familiar with Java persistence using JPA and Hibernate.

    Multitenancy architecture

    Multitenancy is an architecture that permits a single application to serve multiple tenants, also known as clients. Although tenants in a multitenancy architecture access the same application, they are securely isolated from each other. Furthermore, each tenant only has access to its own resources. Multitenancy is a common architectural approach for software-as-a-service (SaaS) and cloud computing applications. In general, clients (or tenants) accessing a SaaS are accessing the same application, but each one is isolated from the others and has its own resources.

    A multitenant architecture must isolate the data available to each tenant. If there is a problem with one tenant's data set, it won't impact the other tenants. In a relational database, we use a database or a schema to isolate each tenant's data. One way to separate data is to give each tenant access to its own database or schema. Another option, which is available if you are using a relational database with JPA and Hibernate, is to partition a single database for multiple tenants. In this article, I focus on the standalone database and schema options. I won't demonstrate how to set up a partition.

    In a server-based application like WildFly, multitenancy is different from the conventional approach. In this case, the server application works directly with the data source by initiating a connection and preparing the database to be used. The client application does not spend time opening the connection, which improves performance. On the other hand, using Enterprise JavaBeans (EJBs) for container-managed transactions can lead to problems. As an example, the server-based application could do something to generate an error to commit or roll the application back.

    Implementation code

    Two interfaces are crucial to implementing multitenancy in JPA and Hibernate:

    • MultiTenantConnectionProvider is responsible for connecting tenants to their respective databases and services. We will use this interface and a tenant identifier to switch between databases for different tenants.
    • CurrentTenantIdentifierResolver is responsible for identifying the tenant. We will use this interface to define what is considered a tenant (more about this later). We will also use this interface to provide the correct tenant identifier to MultiTenantConnectionProvider.

    In JPA, we configure these interfaces using the persistence.xml file. In the next sections, I'll show you how to use these two interfaces to create the first three classes we need for our multitenancy architecture: DatabaseMultiTenantProvider, MultiTenantResolver, and DatabaseTenantResolver.

    DatabaseMultiTenantProvider

    DatabaseMultiTenantProvider is an implementation of the MultiTenantConnectionProvider interface. This class contains logic to switch to the database that matches the given tenant identifier. In WildFly, this means switching to different data sources. The DatabaseMultiTenantProvider class also implements the ServiceRegistryAwareService, which allows us to inject a service during the configuration phase.

    Here's the code for the DatabaseMultiTenantProvider class:

    public class DatabaseMultiTenantProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService{
        private static final long serialVersionUID = 1L;
        private static final String TENANT_SUPPORTED = "DATABASE";
        private DataSource dataSource;
        private String typeTenancy ;
    
        @Override
        public boolean supportsAggressiveRelease() {
            return false;
        }
        @Override
        public void injectServices(ServiceRegistryImplementor serviceRegistry) {
    
            typeTenancy = (String) ((ConfigurationService)serviceRegistry
                    .getService(ConfigurationService.class))
                    .getSettings().get("hibernate.multiTenancy");
    
            dataSource = (DataSource) ((ConfigurationService)serviceRegistry
                    .getService(ConfigurationService.class))
                    .getSettings().get("hibernate.connection.datasource");
    
    
        }
        @SuppressWarnings("rawtypes")
        @Override
        public boolean isUnwrappableAs(Class clazz) {
            return false;
        }
        @Override
        public <T> T unwrap(Class<T> clazz) {
            return null;
        }
        @Override
        public Connection getAnyConnection() throws SQLException {
            final Connection connection = dataSource.getConnection();
            return connection;
    
        }
        @Override
        public Connection getConnection(String tenantIdentifier) throws SQLException {
    
            final Context init;
            //Just use the multi-tenancy if the hibernate.multiTenancy == DATABASE
            if(TENANT_SUPPORTED.equals(typeTenancy)) {
                try {
                    init = new InitialContext();
                    dataSource = (DataSource) init.lookup("java:/jdbc/" + tenantIdentifier);
                } catch (NamingException e) {
                    throw new HibernateException("Error trying to get datasource ['java:/jdbc/" + tenantIdentifier + "']", e);
                }
            }
    
            return dataSource.getConnection();
        }
    
        @Override
        public void releaseAnyConnection(Connection connection) throws SQLException {
            connection.close();
        }
        @Override
        public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
            releaseAnyConnection(connection);
        }
    }
    

    As you can see, we call the injectServices method to populate the datasource and typeTenancy attributes. We use the datasource attribute to get a connection from the data source, and we use the typeTenancy attribute to find out if the class supports the multiTenancy type. We call the getConnection method to get a data source connection. This method uses the tenant identifier to locate and switch to the correct data source.

    MultiTenantResolver

    MultiTenantResolver is an abstract class that implements the CurrentTenantIdentifierResolver interface. This class aims to provide a setTenantIdentifier method to all CurrentTenantIdentifierResolver implementations:

    public abstract class MultiTenantResolver implements CurrentTenantIdentifierResolver {
    
        protected String tenantIdentifier;
    
        public void setTenantIdentifier(String tenantIdentifier) {
            this.tenantIdentifier = tenantIdentifier;
        }
    }
    

    This abstract class is simple. We only use it to provide the setTenantIdentifier method.

    DatabaseTenantResolver

    DatabaseTenantResolver also implements the CurrentTenantIdentifierResolver interface. This class is the concrete class of MultiTenantResolver:

    public class DatabaseTenantResolver extends MuiltiTenantResolver {
    
        private Map<String, String> regionDatasourceMap;
    
        public DatabaseTenantResolver(){
            regionDatasourceMap = new HashMap();
            regionDatasourceMap.put("default", "MyDataSource");
            regionDatasourceMap.put("america", "AmericaDB");
            regionDatasourceMap.put("europa", "EuropaDB");
            regionDatasourceMap.put("asia", "AsiaDB");
        }
    
        @Override
        public String resolveCurrentTenantIdentifier() {
    
    
            if(this.tenantIdentifier != null
                    && regionDatasourceMap.containsKey(this.tenantIdentifier)){
                return regionDatasourceMap.get(this.tenantIdentifier);
            }
    
            return regionDatasourceMap.get("default");
    
        }
    
        @Override
        public boolean validateExistingCurrentSessions() {
            return false;
        }
    
    }

    Notice that DatabaseTenantResolver uses a Map to define the correct data source for a given tenant. The tenant, in this case, is a region. Note, too, that this example assumes we have the data sources java:/jdbc/MyDataSource, java:/jdbc/AmericaDB, java:/jdbc/EuropaDB, and java:/jdbc/AsiaDB configured in WildFly.

    Configure and define the tenant

    Now we need to use the persistence.xml file to configure the tenant:

    <persistence>
        <persistence-unit name="jakartaee8">
    
            <jta-data-source>jdbc/MyDataSource</jta-data-source>
            <properties>
                <property name="javax.persistence.schema-generation.database.action" value="none" />
                <property name="hibernate.dialect" value="org.hibernate.dialect.PostgresPlusDialect"/>
                <property name="hibernate.multiTenancy" value="DATABASE"/>
                <property name="hibernate.tenant_identifier_resolver" value="net.rhuanrocha.dao.multitenancy.DatabaseTenantResolver"/>
                <property name="hibernate.multi_tenant_connection_provider" value="net.rhuanrocha.dao.multitenancy.DatabaseMultiTenantProvider"/>
            </properties>
    
        </persistence-unit>
    </persistence>
    

    Next, we define the tenant in the EntityManagerFactory:

    @PersistenceUnit
    protected EntityManagerFactory emf;
    
    
    protected EntityManager getEntityManager(String multitenancyIdentifier){
    
        final MuiltiTenantResolver tenantResolver = (MuiltiTenantResolver) ((SessionFactoryImplementor) emf).getCurrentTenantIdentifierResolver();
        tenantResolver.setTenantIdentifier(multitenancyIdentifier);
    
        return emf.createEntityManager();
    }
    

    Note that we call the setTenantIdentifier before creating a new instance of EntityManager.

    Conclusion

    I have presented a simple example of multitenancy in a database using JPA with Hibernate and WildFly. There are many ways to use a database for multitenancy. My main point has been to show you how to implement the CurrentTenantIdentifierResolver and MultiTenantConnectionProvider interfaces. I've shown you how to use JPA's persistence.xml file to configure the required classes based on these interfaces.

    Keep in mind that for this example, I have assumed that WildFly manages the data source and connection pool and that EJB handles the container-managed transactions. In the second half of this series, I will provide a similar introduction to multitenancy, but using a schema rather than a database. If you want to go deeper with this example, you can find the complete application code and further instructions on my GitHub repository.

    Last updated: November 12, 2020

    Recent Posts

    • More Essential AI tutorials for Node.js Developers

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue