diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml index 63e0799281..c501b7f11d 100644 --- a/hibernate5/pom.xml +++ b/hibernate5/pom.xml @@ -15,6 +15,8 @@ http://maven.apache.org UTF-8 + + 3.6.0 @@ -22,6 +24,11 @@ hibernate-core 5.2.9.Final + + junit + junit + 4.12 + com.h2database h2 @@ -37,6 +44,32 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java index c3e7b621d0..5a10b2ba56 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java @@ -1,5 +1,9 @@ package com.baeldung.hibernate; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -20,44 +24,56 @@ import com.baeldung.hibernate.pojo.Supplier; public class HibernateMultiTenantUtil { private static SessionFactory sessionFactory; private static Map connectionProviderMap = new HashMap<>(); - private static final String[] tenantDBNames = { "mydb1","mydb2"}; + private static final String[] tenantDBNames = { "mydb1", "mydb2" }; - public static SessionFactory getSessionFactory() throws UnsupportedTenancyException { + public static SessionFactory getSessionFactory() throws UnsupportedTenancyException, IOException { if (sessionFactory == null) { - Configuration configuration = new Configuration().configure(); - ServiceRegistry serviceRegistry = configureServiceRegistry(configuration); - sessionFactory = makeSessionFactory (serviceRegistry); -// sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - + // Configuration configuration = new Configuration().configure(); + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } return sessionFactory; } private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { - MetadataSources metadataSources = new MetadataSources( serviceRegistry ); - for(Class annotatedClasses : getAnnotatedClasses()) { - metadataSources.addAnnotatedClass( annotatedClasses ); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + for (Class annotatedClasses : getAnnotatedClasses()) { + metadataSources.addAnnotatedClass(annotatedClasses); } Metadata metadata = metadataSources.buildMetadata(); - return metadata.getSessionFactoryBuilder().build(); - + return metadata.getSessionFactoryBuilder() + .build(); + } private static Class[] getAnnotatedClasses() { - return new Class[] { - Supplier.class - }; + return new Class[] { Supplier.class }; } - private static ServiceRegistry configureServiceRegistry(Configuration configuration) throws UnsupportedTenancyException { - Properties properties = configuration.getProperties(); + private static ServiceRegistry configureServiceRegistry() throws UnsupportedTenancyException, IOException { + + // Properties properties = configuration.getProperties(); + Properties properties = getProperties(); connectionProviderMap = setUpConnectionProviders(properties, tenantDBNames); properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, new ConfigurableMultiTenantConnectionProvider(connectionProviderMap)); - return new StandardServiceRegistryBuilder().applySettings(properties).build(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + FileInputStream inputStream = new FileInputStream(propertiesURL.getFile()); + properties.load(inputStream); + System.out.println("LOADED PROPERTIES FROM hibernate.properties"); + + return properties; } private static Map setUpConnectionProviders(Properties properties, String[] tenantNames) throws UnsupportedTenancyException { @@ -66,23 +82,27 @@ public class HibernateMultiTenantUtil { DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); String tenantStrategy = properties.getProperty("hibernate.multiTenancy"); - System.out.println("Strategy:"+tenantStrategy); + System.out.println("Strategy:" + tenantStrategy); properties.put(Environment.URL, tenantUrl(properties.getProperty(Environment.URL), tenant, tenantStrategy)); - System.out.println("URL:"+properties.getProperty(Environment.URL)); + System.out.println("URL:" + properties.getProperty(Environment.URL)); connectionProvider.configure(properties); - System.out.println("Tenant:"+tenant); + System.out.println("Tenant:" + tenant); providerMap.put(tenant, connectionProvider); - + } System.out.println("Added connections for:"); - providerMap.keySet().stream().forEach(System.out::println); + providerMap.keySet() + .stream() + .forEach(System.out::println); return providerMap; } private static Object tenantUrl(String originalUrl, String tenant, String tenantStrategy) throws UnsupportedTenancyException { - if (tenantStrategy.toUpperCase().equals("DATABASE")) { + if (tenantStrategy.toUpperCase() + .equals("DATABASE")) { return originalUrl.replace(DEFAULT_DB_NAME, tenant); - } else if (tenantStrategy.toUpperCase().equals("SCHEMA")) { + } else if (tenantStrategy.toUpperCase() + .equals("SCHEMA")) { return originalUrl + String.format(SCHEMA_TOKEN, tenant); } else { throw new UnsupportedTenancyException("Not yet supported"); diff --git a/hibernate5/src/main/resources/hibernate.cfg.xml b/hibernate5/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index 26be05f931..0000000000 --- a/hibernate5/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - org.h2.Driver - jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 - sa - - org.hibernate.dialect.H2Dialect - DATABASE - - diff --git a/hibernate5/src/main/resources/hibernate.properties b/hibernate5/src/main/resources/hibernate.properties new file mode 100644 index 0000000000..a8f927a280 --- /dev/null +++ b/hibernate5/src/main/resources/hibernate.properties @@ -0,0 +1,8 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.multiTenancy=DATABASE diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java index 8f2e88ac3d..610617cb8d 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java @@ -1,65 +1,71 @@ package com.baeldung.hibernate; -import com.baeldung.hibernate.pojo.Supplier; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.junit.Test; import static org.junit.Assert.assertNotEquals; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.pojo.Supplier; public class MultiTenantHibernateIntegrationTest { @Test - public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () { - SessionFactory sessionFactory; - try { - sessionFactory = HibernateMultiTenantUtil.getSessionFactory(); - - Session db1Session = sessionFactory - .withOptions().tenantIdentifier("mydb1").openSession(); - - initDb1(db1Session); - - Transaction transaction = db1Session.getTransaction(); - transaction.begin(); - Supplier supplierFromDB1 = (Supplier)db1Session.createCriteria(Supplier.class).list().get(0); - transaction.commit(); - - Session db2Session = sessionFactory - .withOptions().tenantIdentifier("mydb2").openSession(); - - initDb2(db2Session); - db2Session.getTransaction().begin(); - Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0); - db2Session.getTransaction().commit(); - - System.out.println(supplierFromDB1); - System.out.println(supplierFromDB2); - - assertNotEquals(supplierFromDB1, supplierFromDB2); - } catch (UnsupportedTenancyException e) { - e.printStackTrace(); - } + public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs() throws UnsupportedTenancyException, IOException { + SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory(); + + Session db1Session = sessionFactory.withOptions().tenantIdentifier("mydb1").openSession(); + + initDb1(db1Session); + + Transaction transaction = db1Session.getTransaction(); + transaction.begin(); + Supplier supplierFromDB1 = (Supplier) db1Session.createCriteria(Supplier.class).list().get(0); + transaction.commit(); + + Session db2Session = sessionFactory.withOptions().tenantIdentifier("mydb2").openSession(); + + initDb2(db2Session); + db2Session.getTransaction().begin(); + Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0); + db2Session.getTransaction().commit(); + + System.out.println(supplierFromDB1); + System.out.println(supplierFromDB2); + + assertNotEquals(supplierFromDB1, supplierFromDB2); + } - - private void initDb1(Session db1Session) { System.out.println("Init DB1"); Transaction transaction = db1Session.getTransaction(); transaction.begin(); db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate(); - db1Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate(); + db1Session + .createSQLQuery( + "create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))") + .executeUpdate(); db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate(); transaction.commit(); } - + private void initDb2(Session db2Session) { System.out.println("Init DB2"); Transaction transaction = db2Session.getTransaction(); transaction.begin(); db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate(); - db2Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate(); + db2Session + .createSQLQuery( + "create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))") + .executeUpdate(); db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate(); transaction.commit(); } diff --git a/hibernate5/src/test/java/hibernate.properties b/hibernate5/src/test/java/hibernate.properties new file mode 100644 index 0000000000..a8f927a280 --- /dev/null +++ b/hibernate5/src/test/java/hibernate.properties @@ -0,0 +1,8 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.multiTenancy=DATABASE