Skip to content

Commit efd2c2b

Browse files
joshiparthinKevinGilmore
authored andcommitted
Hibernate5 multitenancy changing to hibernate.properties config file. (eugenp#1881)
* First commit for Hibernate 5 Multitenancy tutorial * Changes to fix the code. * Added hibernate begin transaction code. * Changes to solve the multitenancy issue. * Changes to integrate h2 * Changing configs to solve the error * Changes to solve h2 error... * Changes to fix H2 error. * Cleaned POM.xml and changed entity name * Changes table name to supplier * Removed MySql Dep from pom.xml. * Changes as per comment in the PR... * Removed try-catch from test functions. * Removing the hibernate xml config. * Changed the formatting as per the formatter. * Clean up after merge. * # WARNING: head commit changed in the meantime Merge remote-tracking branch 'upstream/master' into hibernate5-multitenancy Conflicts: hibernate5/pom.xml pom.xml
1 parent 8c8c01e commit efd2c2b

6 files changed

Lines changed: 138 additions & 77 deletions

File tree

‎hibernate5/pom.xml‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,20 @@
1515
<url>http://maven.apache.org</url>
1616
<properties>
1717
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18+
<!-- Maven plugins -->
19+
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
1820
</properties>
1921
<dependencies>
2022
<dependency>
2123
<groupId>org.hibernate</groupId>
2224
<artifactId>hibernate-core</artifactId>
2325
<version>5.2.9.Final</version>
2426
</dependency>
27+
<dependency>
28+
<groupId>junit</groupId>
29+
<artifactId>junit</artifactId>
30+
<version>4.12</version>
31+
</dependency>
2532
<dependency>
2633
<groupId>com.h2database</groupId>
2734
<artifactId>h2</artifactId>
@@ -37,6 +44,32 @@
3744
</resource>
3845
</resources>
3946

47+
<plugins>
48+
<plugin>
49+
<groupId>org.apache.maven.plugins</groupId>
50+
<artifactId>maven-compiler-plugin</artifactId>
51+
<version>${maven-compiler-plugin.version}</version>
52+
<configuration>
53+
<source>1.8</source>
54+
<target>1.8</target>
55+
</configuration>
56+
</plugin>
57+
58+
<plugin>
59+
<groupId>org.apache.maven.plugins</groupId>
60+
<artifactId>maven-surefire-plugin</artifactId>
61+
<configuration>
62+
<forkCount>3</forkCount>
63+
<reuseForks>true</reuseForks>
64+
<excludes>
65+
<exclude>**/*IntegrationTest.java</exclude>
66+
<exclude>**/*LiveTest.java</exclude>
67+
</excludes>
68+
</configuration>
69+
</plugin>
70+
71+
</plugins>
72+
4073
</build>
4174

4275
</project>

‎hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java‎

Lines changed: 46 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package com.baeldung.hibernate;
22

3+
import java.io.FileInputStream;
4+
import java.io.FileNotFoundException;
5+
import java.io.IOException;
6+
import java.net.URL;
37
import java.util.HashMap;
48
import java.util.Map;
59
import java.util.Properties;
@@ -20,44 +24,56 @@
2024
public class HibernateMultiTenantUtil {
2125
private static SessionFactory sessionFactory;
2226
private static Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>();
23-
private static final String[] tenantDBNames = { "mydb1","mydb2"};
27+
private static final String[] tenantDBNames = { "mydb1", "mydb2" };
2428

25-
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException {
29+
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException, IOException {
2630
if (sessionFactory == null) {
27-
Configuration configuration = new Configuration().configure();
28-
ServiceRegistry serviceRegistry = configureServiceRegistry(configuration);
29-
sessionFactory = makeSessionFactory (serviceRegistry);
30-
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
31-
32-
31+
// Configuration configuration = new Configuration().configure();
32+
ServiceRegistry serviceRegistry = configureServiceRegistry();
33+
sessionFactory = makeSessionFactory(serviceRegistry);
34+
3335
}
3436
return sessionFactory;
3537
}
3638

3739
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
38-
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
39-
for(Class annotatedClasses : getAnnotatedClasses()) {
40-
metadataSources.addAnnotatedClass( annotatedClasses );
40+
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
41+
for (Class annotatedClasses : getAnnotatedClasses()) {
42+
metadataSources.addAnnotatedClass(annotatedClasses);
4143
}
4244

4345
Metadata metadata = metadataSources.buildMetadata();
44-
return metadata.getSessionFactoryBuilder().build();
45-
46+
return metadata.getSessionFactoryBuilder()
47+
.build();
48+
4649
}
4750

4851
private static Class<?>[] getAnnotatedClasses() {
49-
return new Class<?>[] {
50-
Supplier.class
51-
};
52+
return new Class<?>[] { Supplier.class };
5253
}
5354

54-
private static ServiceRegistry configureServiceRegistry(Configuration configuration) throws UnsupportedTenancyException {
55-
Properties properties = configuration.getProperties();
55+
private static ServiceRegistry configureServiceRegistry() throws UnsupportedTenancyException, IOException {
56+
57+
// Properties properties = configuration.getProperties();
58+
Properties properties = getProperties();
5659

5760
connectionProviderMap = setUpConnectionProviders(properties, tenantDBNames);
5861
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, new ConfigurableMultiTenantConnectionProvider(connectionProviderMap));
5962

60-
return new StandardServiceRegistryBuilder().applySettings(properties).build();
63+
return new StandardServiceRegistryBuilder().applySettings(properties)
64+
.build();
65+
}
66+
67+
private static Properties getProperties() throws IOException {
68+
Properties properties = new Properties();
69+
URL propertiesURL = Thread.currentThread()
70+
.getContextClassLoader()
71+
.getResource("hibernate.properties");
72+
FileInputStream inputStream = new FileInputStream(propertiesURL.getFile());
73+
properties.load(inputStream);
74+
System.out.println("LOADED PROPERTIES FROM hibernate.properties");
75+
76+
return properties;
6177
}
6278

6379
private static Map<String, ConnectionProvider> setUpConnectionProviders(Properties properties, String[] tenantNames) throws UnsupportedTenancyException {
@@ -66,23 +82,27 @@ private static Map<String, ConnectionProvider> setUpConnectionProviders(Properti
6682
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
6783

6884
String tenantStrategy = properties.getProperty("hibernate.multiTenancy");
69-
System.out.println("Strategy:"+tenantStrategy);
85+
System.out.println("Strategy:" + tenantStrategy);
7086
properties.put(Environment.URL, tenantUrl(properties.getProperty(Environment.URL), tenant, tenantStrategy));
71-
System.out.println("URL:"+properties.getProperty(Environment.URL));
87+
System.out.println("URL:" + properties.getProperty(Environment.URL));
7288
connectionProvider.configure(properties);
73-
System.out.println("Tenant:"+tenant);
89+
System.out.println("Tenant:" + tenant);
7490
providerMap.put(tenant, connectionProvider);
75-
91+
7692
}
7793
System.out.println("Added connections for:");
78-
providerMap.keySet().stream().forEach(System.out::println);
94+
providerMap.keySet()
95+
.stream()
96+
.forEach(System.out::println);
7997
return providerMap;
8098
}
8199

82100
private static Object tenantUrl(String originalUrl, String tenant, String tenantStrategy) throws UnsupportedTenancyException {
83-
if (tenantStrategy.toUpperCase().equals("DATABASE")) {
101+
if (tenantStrategy.toUpperCase()
102+
.equals("DATABASE")) {
84103
return originalUrl.replace(DEFAULT_DB_NAME, tenant);
85-
} else if (tenantStrategy.toUpperCase().equals("SCHEMA")) {
104+
} else if (tenantStrategy.toUpperCase()
105+
.equals("SCHEMA")) {
86106
return originalUrl + String.format(SCHEMA_TOKEN, tenant);
87107
} else {
88108
throw new UnsupportedTenancyException("Not yet supported");

‎hibernate5/src/main/resources/hibernate.cfg.xml‎

Lines changed: 0 additions & 14 deletions
This file was deleted.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
hibernate.connection.driver_class=org.h2.Driver
2+
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
3+
hibernate.connection.username=sa
4+
jdbc.password=
5+
6+
hibernate.dialect=org.hibernate.dialect.H2Dialect
7+
hibernate.show_sql=true
8+
hibernate.multiTenancy=DATABASE

‎hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java‎

Lines changed: 43 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,71 @@
11
package com.baeldung.hibernate;
2-
import com.baeldung.hibernate.pojo.Supplier;
2+
3+
import static org.junit.Assert.assertNotEquals;
4+
5+
import java.io.IOException;
6+
import java.sql.Connection;
7+
import java.sql.DriverManager;
8+
import java.sql.SQLException;
9+
import java.sql.Statement;
10+
311
import org.hibernate.Session;
412
import org.hibernate.SessionFactory;
513
import org.hibernate.Transaction;
14+
import org.junit.Before;
615
import org.junit.Test;
716

8-
import static org.junit.Assert.assertNotEquals;
9-
17+
import com.baeldung.hibernate.pojo.Supplier;
1018

1119
public class MultiTenantHibernateIntegrationTest {
1220
@Test
13-
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () {
14-
SessionFactory sessionFactory;
15-
try {
16-
sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
17-
18-
Session db1Session = sessionFactory
19-
.withOptions().tenantIdentifier("mydb1").openSession();
20-
21-
initDb1(db1Session);
22-
23-
Transaction transaction = db1Session.getTransaction();
24-
transaction.begin();
25-
Supplier supplierFromDB1 = (Supplier)db1Session.createCriteria(Supplier.class).list().get(0);
26-
transaction.commit();
27-
28-
Session db2Session = sessionFactory
29-
.withOptions().tenantIdentifier("mydb2").openSession();
30-
31-
initDb2(db2Session);
32-
db2Session.getTransaction().begin();
33-
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
34-
db2Session.getTransaction().commit();
35-
36-
System.out.println(supplierFromDB1);
37-
System.out.println(supplierFromDB2);
38-
39-
assertNotEquals(supplierFromDB1, supplierFromDB2);
40-
} catch (UnsupportedTenancyException e) {
41-
e.printStackTrace();
42-
}
43-
}
21+
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs() throws UnsupportedTenancyException, IOException {
22+
SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
23+
24+
Session db1Session = sessionFactory.withOptions().tenantIdentifier("mydb1").openSession();
4425

26+
initDb1(db1Session);
4527

28+
Transaction transaction = db1Session.getTransaction();
29+
transaction.begin();
30+
Supplier supplierFromDB1 = (Supplier) db1Session.createCriteria(Supplier.class).list().get(0);
31+
transaction.commit();
32+
33+
Session db2Session = sessionFactory.withOptions().tenantIdentifier("mydb2").openSession();
34+
35+
initDb2(db2Session);
36+
db2Session.getTransaction().begin();
37+
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
38+
db2Session.getTransaction().commit();
39+
40+
System.out.println(supplierFromDB1);
41+
System.out.println(supplierFromDB2);
42+
43+
assertNotEquals(supplierFromDB1, supplierFromDB2);
44+
45+
}
4646

4747
private void initDb1(Session db1Session) {
4848
System.out.println("Init DB1");
4949
Transaction transaction = db1Session.getTransaction();
5050
transaction.begin();
5151
db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
52-
db1Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
52+
db1Session
53+
.createSQLQuery(
54+
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
55+
.executeUpdate();
5356
db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate();
5457
transaction.commit();
5558
}
56-
59+
5760
private void initDb2(Session db2Session) {
5861
System.out.println("Init DB2");
5962
Transaction transaction = db2Session.getTransaction();
6063
transaction.begin();
6164
db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
62-
db2Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
65+
db2Session
66+
.createSQLQuery(
67+
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
68+
.executeUpdate();
6369
db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate();
6470
transaction.commit();
6571
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
hibernate.connection.driver_class=org.h2.Driver
2+
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
3+
hibernate.connection.username=sa
4+
jdbc.password=
5+
6+
hibernate.dialect=org.hibernate.dialect.H2Dialect
7+
hibernate.show_sql=true
8+
hibernate.multiTenancy=DATABASE

0 commit comments

Comments
 (0)