Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Jakarta EE: Multitenancy with JPA on WildFly, Part 1

June 15, 2020
Rhuan Rocha
Related topics:
JavaContainersDevOps

    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

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.