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 2

November 12, 2020
Rhuan Rocha
Related topics:
JavaContainersDevOpsOpen source

Share:

    This is the second half of a two-part article about multitenancy with the Jakarta Persistence API (JPA) on WildFly. In Part 1, I showed you how to implement multitenancy using a database. In Part 2, I'll show you how to implement multitenancy using a schema and the Jakarta Persistence API (JPA) on WildFly. You'll learn how to implement JPA's CurrentTenantIdentifierResolver and MultiTenantConnectionProvider interfaces, and how to use JPA’s persistence.xml file to configure the required classes based on these interfaces.

    Implementation code

    The first part of this article offers a conceptual overview of multitenancy with JPA on WildFly and an example of multitenancy using a database. This second part shifts the focus to multitenancy using a schema and JPA. In this case, I assume that WildFly manages the data source and connection pool and that EJB (Jakarta Enterprise Beans) handles the container-managed transactions.

    Two interfaces for multitenancy

    As I explained in my previous article, two interfaces are crucial for implementing multitenancy in JPA and Hibernate:

    • The MultiTenantConnectionProvider interface 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) and to provide the correct tenant identifier to MultiTenantConnectionProvider.

    Next, we'll look at the three classes that implement these interfaces.

    SchemaMultiTenantProvider

    SchemaMultiTenantProvider is an implementation of the MultiTenantConnectionProvider interface. This class contains logic to switch to the schema that matches the given tenant identifier.

    The SchemaMultiTenantProvider class also implements the ServiceRegistryAwareService, which allows us to inject a service during the configuration phase. Here’s the code for the SchemaMultiTenantProvider class:

    public class SchemaMultiTenantProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService {
    
        private static final long serialVersionUID = 1L;
        private static final String TENANT_SUPPORTED = "SCHEMA";
        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();
            resetConnection(connection);// To make sure the connection start using schema/database default.
            return connection;
        }
    
        @Override
        public Connection getConnection(String tenantIdentifier) throws SQLException {
            //Just use the multitenancy if the hibernate.multiTenancy == SCHEMA
            if(TENANT_SUPPORTED.equals(typeTenancy)) {
                try {
                    final Connection connection = getAnyConnection();
                    connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
                    return connection;
                } catch (final SQLException e) {
                     throw new HibernateException("Error trying to alter schema [" + tenantIdentifier + "]", e);
                }
            }
    
            return getAnyConnection();
        }
    
    
    
        @Override
        public void releaseAnyConnection(Connection connection) throws SQLException {
            //As the Wildfly/JBoss has the Container-Managed Container change the SCHEMA in the end can be dangerous (SET SCHEMA 'public').
            //Thus it just closes the connection.
            connection.close();
        }
    
        private void resetConnection(Connection connection){
            if(TENANT_SUPPORTED.equals(typeTenancy)) {
                try {
                    connection.createStatement().execute("SET SCHEMA 'public'");
                } catch (final SQLException e) {
                    throw new HibernateException("Error trying to alter schema [public]", e);
                }
            }
        }
    
        @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 schema.

    MultiTenantResolver

    MultiTenantResolver is a simple, 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;
        }
    }
    

    We only use this class to provide the setTenantIdentifier method.

    SchemaTenantResolver

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

    public class SchemaTenantResolver extends MuiltiTenantResolver {
    
        private Map<String, String> userDatasourceMap;
    
        public SchemaTenantResolver(){
            userDatasourceMap = new HashMap();
            userDatasourceMap.put("default", "public");
            userDatasourceMap.put("username1", "usernameone");
            userDatasourceMap.put("username2", "usernametwo");
    
        }
    
        @Override
        public String resolveCurrentTenantIdentifier() {
            if(this.tenantIdentifier != null
                    && userDatasourceMap.containsKey(this.tenantIdentifier)){
                return userDatasourceMap.get(this.tenantIdentifier);
            }
    
            return userDatasourceMap.get("default");
        }
    
        @Override
        public boolean validateExistingCurrentSessions() {
            return false;
        }
    
    }
    

    Notice that SchemaTenantResolver uses a Map to define the correct schema for a given tenant. The tenant, in this case, is mapped by the user.

    Configure and define the tenant

    Now, we need to use JPA's 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="SCHEMA"/>
                <property name="hibernate.tenant_identifier_resolver" value="net.rhuanrocha.dao.multitenancy.SchemaTenantResolver"/>
                <property name="hibernate.multi_tenant_connection_provider" value="net.rhuanrocha.dao.multitenancy.SchemaMultiTenantProvider"/>
            </properties>
    
        </persistence-unit>
    </persistence>
    

    We define the tenant in the JPA and Hibernate 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

    This article presented a simple example of multitenancy using a schema in a database. There are many ways to use a database for multitenancy. My point has been to show you how to implement the CurrentTenantIdentifierResolver and MultiTenantConnectionProvider interfaces. I've also shown you how to use JPA's persistence.xml to configure the required classes based on the two interfaces.

    Keep in mind that for this example, I have assumed that WildFly manages the data source and connection pool and that we're using enterprise beans for the container-managed transactions. If you want to go deeper with this example, you can find the complete application code and further instructions on my GitHub repository.

    Recent Posts

    • How Kafka improves agentic AI

    • How to use service mesh to improve AI model security

    • How to run AI models in cloud development environments

    • How Trilio secures OpenShift virtual machines and containers

    • How to implement observability with Node.js and Llama Stack

    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